I have two classes, Database
and DatabaseEnc
. I have a function which accepts Database class instance as a parameter. How do I ensure that the function only accepts Database class instance and not any other.
I know I can use instance of
to check if instance is of Database inside the checkConn function. But I am looking for a more typescript based solution.
/* database.ts */
class Database {
public state: string = null;
constructor(state: string) {
this.state = "some state";
}
}
export default Database;
/* database_enc.ts */
class DatabaseEnc {
public state: string = null;
constructor() {
this.state = "some other state";
}
}
export default DatabaseEnc;
/* provider.ts */
import Database from "./database";
import DatabaseEnc from "./database_enc";
function checkConn(db: Database): void {
Log.print(db);
}
// wrong, I should not be allowed to pass DatabaseEnc
// instance to the checkConn function parameter
const test = new DatabaseEnc();
checkConn(test);
// right, checkConn function should only accept Database
// class instance as a parameter
const test1 = new Database();
checkConn(test1);
// what is happening? I am allowed to pass any class's instance
// to the checkConn function.
I should not be allowed to pass any instance other than Database to the checkConn
function.