How to define static property in TypeScript interface

前端 未结 14 1169
你的背包
你的背包 2020-11-28 05:49

I just want to declare a static property in typescript interface? I have not found anywhere regarding this.

interface myInterface {
  static         


        
相关标签:
14条回答
  • 2020-11-28 06:21

    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); 
    
    0 讨论(0)
  • 2020-11-28 06:23

    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());
    
    0 讨论(0)
提交回复
热议问题