首页 > 解决方案 > 如何为静态类成员提供类型

问题描述

我有一组类,它们都应该有一些共同的属性和类型限制。

想想如何Uint8ArrayUint16Array相似。

比较它们时首先想到的可能是:

interface TypedArray {
    static of(...args: number[]): TypedArray;
    static from(args: IterableIterator<number>): TypedArray;
    [index: number]: number;
}

class Uint8Array implements TypedArray {
    ...
}

class Uint16Array implements TypedArray {
    ...
}

我认为通用接口会描述我想要的内容,但是接口中不允许使用静态成员。

How to define static property in TypeScript interface的问题与此有些相似,但提供的解决方案都不适用于我正在做的事情,而且我并不特别关心解决方案是否使用接口。

任何使所有类都比它们必须的更通用的情况都不适合我的使用。

考虑以下情况,我想要最具体的类型:

interface X {
    // static prop(): number;
    foo?(): void;
    bar?(): void;
}

class Y implements X {
    static prop() { return 2; }
    foo() {};
    // bar: undefined
}

new Y().foo(); // okay

class Z implements X {
    static prop() { return 4; }
     // foo: undefined
    bar() {};
}

new Z().foo(); // error

相反,如果我要做这样的事情:

interface I {
    prop?(): void;
}

const C: I = class {
    static prop() {}
}

我现在会丢失有关实际类的信息,因为实际上它确实具有该prop方法。

但这并没有解决类的静态属性,我怎样才能为两者提供一个类型?

此外,我的类是从其他类扩展而来的,所以抽象类不适合这里。

标签: typescript

解决方案


推荐阅读