首页 > 解决方案 > 为什么打字稿抱怨计算的属性名称?

问题描述

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

请参阅typescript playground 中的实际代码。

标签: typescript

解决方案


第一个定义是映射类型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'.错误)


推荐阅读