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()
接口检查类的静态属性(在我的示例中)?
解决方案
您不能拥有接口的静态实现。当您将类分配给接口的类型化变量时,您可以得到该类满足接口的事实:
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;
}
推荐阅读
- angular - 离开输入控件时如何触发 *ngIf 指令进行验证
- dart - StreamBuilder 抛出 Dirty State 说 Invalid Arguments
- jhipster - 生成后如何禁用 Jhipster 本地存储库自动提交功能?
- powershell - 通过powershell脚本重新排序章鱼步骤
- node.js - 如何在 Nodejs 中使用 POST 请求 HTTP/2 AWS API 流式传输数据?
- ios - 从数组中过滤数据
- scala - 使用 Akka actor 时异常处理的正确方法
- r - 使用 R 从 Google Drive 下载图像文件
- c# - 如何更改@html.editor,以便在我想添加新数据时可以输入它,而在我想编辑时它会被禁用?
- sql-server - 如何正确检索表 ID