[英]Why does typescript complain about a computed property name?
使用 typescript 版本 3.7.5。 我有這兩種簡單的類型,我希望它們要么編譯要么都不編譯。 但是,typescript 只抱怨第二個。 為什么第二種無效,但第一種無效?
// this works
type foo = {
[key in 'xxx']: number
}
// this does not
type bar = {
xxx: number
[key in 'xxx']: number
}
以下是編譯器消息:
A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)
The right-hand side of an 'in' expression must be of type 'any', an object type or a type parameter.ts(2361)
請參閱typescript 操場中的代碼。
第一個定義是一個映射類型( doc ),它綁定了key
,所以你可以在右邊使用它,例如:
type foo = {
[key in 'xxx']: key
}
但是,您不能將屬性添加到映射類型。 例如,對於
type foo = {
[key in 'xxx']: key
xxx: number
}
TypeScript 將在xxx
的 position 處顯示有關預期}
的錯誤。
另一方面,
type bar = {
xxx: number
[key in 'xxx']: number
}
是一個常規類型文字,其中[key in 'xxx']: number
是一個計算屬性,前兩個錯誤消息中提到的限制適用。
第三條錯誤消息來自 TypeScript 將in
解釋in
. 您可以在此處看到相同的錯誤:
const error = key in 'xxx'
(如果您在第二個示例中使用 hover over key
,您還會看到Cannot find name 'key'.
錯誤)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.