我正在尝试了解Typescript中的界面主题
当我遇到Class类型时,我从official docs得到了这段代码
interface ClockConstructor {
new (hour: number, minute: number);
}
class Clock implements ClockConstructor {
currentTime: Date;
constructor(h: number, m: number) { }
}
我了解到Clock与new签名不符(小时:数字,分钟:数字);这就是为什么我们在那里出现错误.
但是在文档中,解释是我无法理解的.它以这种方式进行:
This is because when a class implements an interface, only the instance side of the class is checked. Since the constructor sits in the static side, it is not included in this check.
任何解释将不胜感激.
解决方法:
接口声明实例具有的方法/成员,而不声明实现类所具有的方法/成员.
例如,检查Array和ArrayConstructor声明:
interface Array<T> {
length: number;
toString(): string;
toLocaleString(): string;
push(...items: T[]): number;
pop(): T | undefined;
...
[n: number]: T;
}
interface ArrayConstructor {
new (arrayLength?: number): any[];
new <T>(arrayLength: number): T[];
new <T>(...items: T[]): T[];
(arrayLength?: number): any[];
<T>(arrayLength: number): T[];
<T>(...items: T[]): T[];
isArray(arg: any): arg is Array<any>;
readonly prototype: Array<any>;
}
如您所见,数组具有在数组的任何实例上存在的方法/成员:
let a = [];
a.push(1, 2, 3);
console.log(a.length);
但是ArrayConstructor具有数组本身上存在的成员/方法:
console.log(Array. prototype);
console.log(Array.isArray(9));
构造函数是“静态”部分的一部分,这就是为什么要在ArrayConstructor中声明它们的原因.
例如,如果在接口上声明构造函数,则在实现该接口时会遇到问题:
interface MyInterface {
constructor();
getName(): string;
}
class MyClass implements MyInterface {
constructor() {}
getName() { return "name" };
}
错误:
Class ‘MyClass’ incorrectly implements interface ‘MyInterface’. Types
of property ‘constructor’ are incompatible. Type ‘Function’ is not
assignable to type ‘() => void’. Type ‘Function’ provides no match for
the signature ‘(): any’.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。