简体   繁体   English

如何在TypeScript中使用动态属性定义对象的类型

[英]How to define type for object with dynamic properties in TypeScript

I have an object which has title as string and order as number, and then there will be dynamic number of properties of type number on it 我有一个对象,其title为字符串, order为数字,然后将有动态数量的类型为数字的属性

So I tried to define it like below 所以我试着像下面这样定义它

appraisalGroups: Array<{
    title: string,
    order: number,
    [key:string]: number,
}>;

and later this will be assigned like this (this is just an example in my read application there will be a loop and keys are coming from a rest api) 以后这将被分配(这只是我的阅读应用程序中的一个例子,将有一个循环,密钥来自其余的api)

this.appraisalGroups[0]['mykey1'] = 5

and I got ts error 我得到了ts错误

Property 'title' of type 'string' is not assignable to string index type 'number' 'string'类型的属性'title'不能赋予字符串索引类型'number'

My question is how can I make it typed? 我的问题是如何键入?

https://stackblitz.com/edit/angular-mzdwmn https://stackblitz.com/edit/angular-mzdwmn

You are getting this because index signatures force all properties to match their return type. 您得到此信息是因为索引签名会强制所有属性与其返回类型匹配。 As stated in Typescript docs: https://www.typescriptlang.org/docs/handbook/interfaces.html 正如Typescript文档中所述: https ://www.typescriptlang.org/docs/handbook/interfaces.html

While string index signatures are a powerful way to describe the dictionary pattern, they also enforce that all properties match their return type. 虽然字符串索引签名是描述字典模式的有效方式,但它们还强制所有属性都与其返回类型匹配。

An index signature is explicitly saying "whenever this object is indexed with a value of this type, it will return a value of that type". 索引签名明确地说“每当使用此类型的值索引此对象时,它将返回该类型的值”。

In your example, your index signature says that "whenever this object is indexed with a string, it will return a number". 在您的示例中,您的索引签名表示“只要此对象使用字符串编制索引,就会返回一个数字”。 However, the compiler sees that this rule can be broken because one of your properties is not a number, so it throws an error. 但是,编译器发现此规则可能会被破坏,因为您的某个属性不是数字,因此会引发错误。

I'm not sure what your problem space is but if the dynamic properties all have something in common, then it might be easier to create an interface to abstract their commonalities away. 我不确定你的问题空间是什么,但如果动态属性都有共同点,那么创建一个接口来抽象它们的共性可能会更容易。 How you use said interface really depends on what you want to do though. 您如何使用所述界面实际上取决于您想要做什么。

EDIT: You could also be cheeky and take a shortcut and simply use a Union type. 编辑:你也可以厚颜无耻,采取捷径,只需使用联盟类型。 So instead of [key:string]: number you do [key:string]: number | string 所以代替[key:string]: number你做的[key:string]: number [key:string]: number | string [key:string]: number | string . [key:string]: number | string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM