首页 > 解决方案 > 如何根据接口检查类的静态属性

问题描述

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()接口检查类的静态属性(在我的示例中)?

标签: typescript

解决方案


您不能拥有接口的静态实现。当您将类分配给接口的类型化变量时,您可以得到该类满足接口的事实:

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;
}

推荐阅读