为什么打字稿会抱怨计算出的属性名称?

时间:2020-04-22 22:55:52

标签: typescript

使用打字稿版本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

1 个答案:

答案 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'.错误)