![](/img/trans.png)
[英]How javascript allows object key type syntax without including ir inside a literal and also variable declaration inside it?
[英]Type declaration works for object literal, but not for class implementation
我想要一个类型来代表一个坐标。 我已应用到接口的类型适用于对象,但不适用于类。
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]
。 显式定义的类型ICoord
对于a
似乎工作:
type ICoord = [number, number];
type MyInterface = {
a: ICoord;
}
class C implements MyInterface {
a: ICoord = [0, 0];
}
这与上下文类型有关。
Typescript使用表达式的预期类型(在这种情况下为MyInterface
)来更好地推断对象文字(还涉及函数参数)。 这就是为什么分配对象文字可以很好地工作并且将数组文字键入为元组类型的原因。
对于班级,情况有所不同。 implements
子句仅用于在类被独立键入后检查类是否正确实现了接口。 implements
关键字不会为任何类成员创建任何上下文类型。 这也是您必须指定函数参数类型的原因,即使它们在接口或基类中是显而易见的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.