我想要一个类型来表示坐标。我应用于接口的类型适用于对象,但不适用于类。
type ICoord = [number, number]
type MyInterface = {
a: ICoord
}
var obj: MyInterface = { // works
a: [0, 0]
}
class C implements MyInterface { // gets below compilation error
a = [0, 0]
}
Property 'a' in type 'C' is not assignable to the same property in base type 'MyInterface'. Type 'number[]' is missing the following properties from type '[number, number]': 0, 1
为什么我无法将[0, 0]
分配给a
?
[打字机游乐场]
a
的类型被推断为number[]
,不能分配给元组[number, number]
。将类型显式定义为a
的ICoord
似乎有效:
type ICoord = [number, number];
type MyInterface = {
a: ICoord;
}
class C implements MyInterface {
a: ICoord = [0, 0];
}
打字稿游乐场
这与上下文类型有关。
Typescript 使用表达式的预期类型(在本例中MyInterface
(来更好地推断对象文字(也包括函数参数(。这就是为什么分配对象文本效果很好,数组文本类型化为元组类型。
对于类来说,情况有点不同。implements
子句仅用于在类独立类型化后检查类是否正确实现了接口。implements
关键字不会为任何类成员创建任何上下文类型。这也是您必须指定函数参数类型的原因,即使它们从接口或基类中很明显。