【发布时间】:2019-10-26 13:53:25
【问题描述】:
这是我的代码
interface clients{
[key: string]: number
}
let x:clients = {}
我不明白为什么我可以为 x 分配一个空对象?
【问题讨论】:
-
您遇到什么错误?刚刚在我的环境中尝试过,我没有看到任何 linting 错误。
标签: typescript
这是我的代码
interface clients{
[key: string]: number
}
let x:clients = {}
我不明白为什么我可以为 x 分配一个空对象?
【问题讨论】:
标签: typescript
为什么不行?
[key: string]: number 基本上是说所有属性键都必须是字符串,值必须是数字。因为对于 JS 对象总是,所有属性键都是字符串,它只是说,这个对象的所有属性值都必须是数字。它没有说明对象必须具有多少属性。这可以是零(如您的示例)或任意多个。
【讨论】:
正如另一个答案中提到的,{ [key: string]: number } 表示该类型的任何索引都会产生一个数字。 {} 更接近于Partial<{ [key: string]: number }> ({ [key: string]: number | undefined })。
您也可以考虑使用Record<string, number>。
{ [key: string]: number | undefined } 是一种更安全的类型,无论如何,尤其是启用strict 模式。当您索引一个类型为该类型的值时,结果变量的类型为number | undefined。它会强制您在 JavaScript 中验证该结果。
const client = x['clientId'] // type = number | undefined
if (client != undefined) {
// typeof client === 'number'
}
【讨论】: