【问题标题】:Why can I assign an empty object types {[key: string]: number}为什么我可以分配一个空对象类型 {[key: string]: number}
【发布时间】:2019-10-26 13:53:25
【问题描述】:

这是我的代码

interface clients{
    [key: string]: number
}
let x:clients = {}

我不明白为什么我可以为 x 分配一个空对象?

【问题讨论】:

标签: typescript


【解决方案1】:

为什么不行?

[key: string]: number 基本上是说所有属性键都必须是字符串,值必须是数字。因为对于 JS 对象总是,所有属性键都是字符串,它只是说,这个对象的所有属性值都必须是数字。它没有说明对象必须具有多少属性。这可以是零(如您的示例)或任意多个。

【讨论】:

    【解决方案2】:

    正如另一个答案中提到的,{ [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'
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 1970-01-01
      • 2020-06-19
      • 2021-11-16
      • 2020-08-07
      • 2023-02-08
      • 2020-06-19
      • 2022-11-14
      • 1970-01-01
      相关资源
      最近更新 更多