I just want to declare a static property in typescript interface? I have not found anywhere regarding this.
interface myInterface {
static
The other solutions seem to stray from the blessed path and I found that my scenario was covered in the Typescript documentation which I've paraphrased below:
interface AppPackageCheck<T> {
new (packageExists: boolean): T
checkIfPackageExists(): boolean;
}
class WebApp {
public static checkIfPackageExists(): boolean {
return false;
}
constructor(public packageExists: boolean) {}
}
class BackendApp {
constructor(public packageExists: boolean) {}
}
function createApp<T>(type: AppPackageCheck<T>): T {
const packageExists = type.checkIfPackageExists();
return new type(packageExists)
}
let web = createApp(WebApp);
// compiler failure here, missing checkIfPackageExists
let backend = createApp(BackendApp);
Static modifiers cannot appear on a type member (TypeScript error TS1070). That's why I recommend to use an abstract class to solve the mission:
Example
// Interface definition
abstract class MyInterface {
static MyName: string;
abstract getText(): string;
}
// Interface implementation
class MyClass extends MyInterface {
static MyName = 'TestName';
getText(): string {
return `This is my name static name "${MyClass.MyName}".`;
}
}
// Test run
const test: MyInterface = new MyClass();
console.log(test.getText());