![](/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.