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)
解决方案
第一个定义是映射类型(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'.
错误)
推荐阅读
- c# - 使用集合属性了解时间复杂度
- python - 阻塞套接字,可以用多处理解决吗?
- go - 使 Firestore 仅返回 customer_id 小于 1000 的用户
- ios - 连接到 NFCTagReaderSession NFCISO7816Tag 标签并在 iOS 13 中发送命令
- matlab - 如何将图形加载和卸载到 matlab 应用程序的轴中?
- javascript - 如何使用 '.replaceWith' 从另一个 html 页面加载数据?
- c# - SQL Server 在 C# 应用程序使用时卡住/锁定简单截断
- python - 如何在 C++ 程序中执行 python 代码
- python - 在 0.95 到 .40 范围内选择多个概率列
- java - 用于基于 Java 的 SOAP Web 服务的 PHP SOAP XML 格式