类的静态和实例方面的区别 [英] Difference between the static and instance sides of classes
问题描述
当我遇到类型时,我试图理解Typescript
中的界面主题,我从官方文档
I am trying to understand interface topic in Typescript when I came across Class type, I got this code from official docs
interface ClockConstructor {
new (hour: number, minute: number);
}
class Clock implements ClockConstructor {
currentTime: Date;
constructor(h: number, m: number) { }
}
我可以理解时钟
与签名 new(小时:数字,分钟:数字)无关;
这就是为什么我们在那里得到一个错误。
I can understand that Clock
has no match for the signature new (hour: number, minute: number);
that's why we get an error there.
但在文档中,解释是我无法理解的。它是这样的:
But in docs the explaination is something which I am unable to understand. It goes in this way :
这是因为当一个类实现一个接口时,只检查该类的实例端。由于构造函数位于静态方面,因此不包括在此检查中。
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.
任何解释都将不胜感激。
Any explanation would be appreciated.
推荐答案
接口声明实例具有的方法/成员,而不是实现类具有的。
The interface declares the method/members that the instances have, and not what the implementing class has.
例如,检查数组和 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>;
}
如你所见,数组
具有存在于任何数组实例上的方法/成员:
As you can see, the Array
has method/members which exist on any instance of array:
let a = [];
a.push(1, 2, 3);
console.log(a.length);
但是 ArrayConstructor
有成员/方法存在于数组
本身:
But the ArrayConstructor
has the members/methods which exist on the Array
itself:
console.log(Array. prototype);
console.log(Array.isArray(9));
构造函数是静态部分的一部分,这就是它们在<$ c中声明的原因$ c> ArrayConstructor 。
如果在接口上声明构造函数,例如,实现该接口时会遇到问题:
The constructors are part of the "static" part which is why they are declared in the ArrayConstructor
.
If you declare a constructor on an interface for example you'll have a problem implementing that interface:
interface MyInterface {
constructor();
getName(): string;
}
class MyClass implements MyInterface {
constructor() {}
getName() { return "name" };
}
错误:
类'MyClass'错误地实现了接口'MyInterface'。类型
属性'constructor'是不兼容的。类型'Function'不是
可分配给'()=> void'。类型'函数'不能为
提供签名'():any'。
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'.
这篇关于类的静态和实例方面的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!