如何根据接口检查类的静态属性

时间:2018-08-04 14:31:39

标签: typescript

JavaScript中的此构造函数:

function C() {
    this.x = 100;
}
C.prototype = {
    constructor: C,
    m() {}
};
C.staticM = function () {};

我已经在TypeScript中进行了转换:

class C {
    x: number;

    constructor() {
        this.x = 100;
    }

    m() {}
    static staticM() {}
}

我还为C()添加了这些接口:

interface CConstructor {
    new (): CInstance;
    staticM(): void;
}

interface CPrototype {
    constructor: CConstructor;
    m(): void;
}

interface CInstance extends CPrototype {
    x: number;
}

但是当我写:

class C implements CInstance {...}

我收到错误消息:

[ts]
Class 'C' incorrectly implements interface 'CInstance'.
Types of property 'constructor' are incompatible.
    Type 'Function' is not assignable to type 'CConstructor'.
    Property 'staticM' is missing in type 'Function'.

如何针对接口检查类(在示例中为staticM())的静态属性?

2 个答案:

答案 0 :(得分:0)

Typescript既不允许在接口中也不允许在抽象类中使用静态属性,这是个老问题:https://github.com/Microsoft/TypeScript/issues/14600

不幸的是,您不应在Typescript中广泛使用静态道具:/

答案 1 :(得分:0)

您不能具有接口的静态实现。当您将类分配给接口的类型变量时,您可能会遇到这样的事实:

class C {
    x: number;

    constructor() {
        this.x = 100;
    }

    m() {}
    static staticM() {}
}

interface CConstructor {
    new (): CInstance;
    staticM(): void;
}

interface CInstance {
    x: number;
    m(): void;
}

let check: CConstructor = C; //error here if implementation is incorrect

或者类似地,您可以使用一个函数来创建类,该类将检查实现是否符合接口

function declareC(cls: CConstructor) {
    return cls;
}


const C = declareC(class {
    x: number;

    constructor() {
        this.x = 100;
    }

    m() { }
    static staticM() { }
});
type C =InstanceType<typeof C>

interface CConstructor {
    new(): CInstance;
    staticM(): void;
}

interface CInstance {
    x: number;
    m(): void;
}