告诉TypeScript该类具有静态和实例方法

时间:2017-05-25 12:55:02

标签: typescript

class A {
    static hasThisMethod: (any) => any
    hasThisMethodToo: (r : any) => any
}

是否可以告诉TypeScript"相信我,在运行时我的类会有这个静态和这个实例方法吗?"

我不想扩展和抽象类,因为那样实际上会将那些方法的空版本放在那里 - 我只想告诉TS"相信我,这些方法存在于运行时"以某种自动方式,所以我不必每次都输出它们,就像我上面那样。

2 个答案:

答案 0 :(得分:0)

也许您正在寻找以下内容?

interface A {
  hasThisMethod: (arg: any) => any;
  new(...args: any[]): { hasThisMethodToo: (r: any) => any };
}

class AImpl {
  static hasThisMethod: (arg: any) => any;
  hasThisMethodToo: (r : any) => any;
}

const a: A = AImpl; // this line compiles successfully

答案 1 :(得分:0)

我暂时会忽略静态方法,但是,可以使用Interface合并告诉Typescript信任您有关在运行时实现的方法的信息。

class MyClass{
    public foo(): number{
        return 1;
    }
}

interface ISomeMethodsYouWantToDeclareYouHaveAtRuntime{
    methodDeclaredInInterface(): string;
}

class SomeOtherActualClass{
    public methodDeclaredInAnotherClass(): string{
        return "hello";
    }
}


// Use declaration merging to tell TS that the MyClass class implements the ISomeEmberClass
interface MyClass extends ISomeMethodsYouWantToDeclareYouHaveAtRuntime{
}

// You can also use declaration merging with another class to say that your class will implement the same methods at runtime
interface MyClass extends SomeOtherActualClass{
}

let instance = new MyClass();

// Allowed
instance.foo();
// Also allowed: (yay!)
instance.methodDeclaredInInterface();
// Also allowed!
instance.methodDeclaredInAnotherClass();

Typescript Playground link

Declaration Merging in the Typescript Handbook