使用打字稿版本3.7.5。我有这两种简单类型,我希望它们要么都编译,要么都不编译。但是,打字稿只抱怨第二个。为什么第二种类型无效,而第一种无效?
// 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)
查看实际使用的代码in the typescript playground。
答案 0 :(得分:0)
第一个定义是映射类型(doc),它绑定key
,因此您可以在右侧使用它,例如:
type foo = {
[key in 'xxx']: key
}
但是您不能将属性添加到映射类型。例如,对于
type foo = {
[key in 'xxx']: key
xxx: number
}
TypeScript将在}
的位置显示有关预期的xxx
的错误。
另一方面,
type bar = {
xxx: number
[key in 'xxx']: number
}
是常规类型的文字,其中[key in 'xxx']: number
是一个计算的属性,前两个错误消息中提到的限制都适用。
第三个错误消息来自TypeScript将in
解释为正则表达式级in
。您可以在此处看到相同的错误:
const error = key in 'xxx'
(如果您在第二个示例中将鼠标悬停在key
上,还会看到一个Cannot find name 'key'.
错误)