typescript - 如何为静态类成员提供类型
问题描述
我有一组类,它们都应该有一些共同的属性和类型限制。
想想如何Uint8Array
和Uint16Array
相似。
比较它们时首先想到的可能是:
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
方法。
但这并没有解决类的静态属性,我怎样才能为两者提供一个类型?
此外,我的类是从其他类扩展而来的,所以抽象类不适合这里。
解决方案
推荐阅读
- node.js - WebRTC Video Track 到 Node 中的 ffmpeg
- reactjs - 使用 Redux 基于按钮单击添加/删除数组中的对象
- ffmpeg - 无效的流说明符:元数据
- python - Tkinter:为什么下一个“标签”的 0 列会有所不同?
- ios - UICollectionViewCompositionalLayout - 具有fractionalWidth 宽度和自定尺寸单元格的意外布局
- python - github get_organization 给出 Not Found Error github.GithubException.UnknownObjectException: 404
- visual-studio-code - 使用 haxe 在 Visual Studio Code 中运行和调试问题
- python - 如何在@tf.function 修饰函数中使用张量作为切片索引?
- python - 我可以找出我的注册表中的错误在哪里吗?
- git - 如何从多个 git 组织中提取存储库