【问题标题】:Can an object containing an array be a type in an Interface's property?包含数组的对象可以是接口属性中的类型吗?
【发布时间】:2021-12-16 00:19:51
【问题描述】:

我正在分析一个 Angular 代码,我遇到了一个 type 和一个 property 和一个名为 'Origin' 的 Interface,我不明白?,这里是:

export interface Origin {       
    areaNum?: number;  
    open?: { [key: string]: any };  
}

我的第一个问题是那是什么样的物体?我认为objects 有一对或多对key:value,其中key 是..,关键:),value 可以包含任何值。这个奇怪的type 似乎是object,但我没有看到key:value,它只包含一个¿array?。在我看来,如果它是 array,因为有方括号,但是 ¿ 数组可以成为 object 的键吗?如何?。我试图弄清楚在创建使用此Interface 的对象时属性open 的外观。我不明白这是什么{ [key: string]: any };。 你能帮我理解吗?,因为我正在学习。如果可能的话,你能给我看一个虚拟的例子object,它使用这个openproperty和一个有效的value,上面奇怪的type?谢谢!

【问题讨论】:

  • 也就是说,Open 是可选的,它的类型是任何对象,但是对象的键必须是字符串,值可以是任何东西。

标签: angular typescript typescript-typings


【解决方案1】:

我的第一个问题是那是什么样的物体?

这是一个有两个可选属性的对象:

  • areaNum,一个数字
  • open,使用index signature 允许字符串索引的对象:该对象可以具有任何字符串名称的属性,并且这些属性的值是any

这是一个代码示例,见 cmets:

export interface Origin {       
    areaNum?: number;  
    open?: { [key: string]: any };  
}

let a: Origin = {
    areaNum: 42,
    open: {}, // <== Valid, an index signature allows there to be no properties
};

if (a.open) {
    // You can do this, because `a.open` has an index signature making
    // any string is a valid property for it:
    a.open["any string you want"] = 42;
    // You *can't* do this, because `a` doesn't have an index signature,
    // it only has `areaNum` and `open` properties:
    a["any string you want"] = 42;
}

Playground link

【讨论】:

    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多