如何在 TypeScript 中为具有动态属性的对象定义类型 [英] How to define type for object with dynamic properties in TypeScript

查看:98
本文介绍了如何在 TypeScript 中为具有动态属性的对象定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,它以title为字符串,order为数字,然后就会有动态数量的number类型的属性

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

所以我试着像下面这样定义

So I tried to define it like below

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

然后这将像这样分配(这只是我的读取应用程序中的一个示例,将有一个循环,并且密钥来自rest api)

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)

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

我得到了 ts 错误

'string' 类型的属性 'title' 不能分配给字符串索引类型 'number'

Property 'title' of type 'string' is not assignable to string index type 'number'

我的问题是如何输入?

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

推荐答案

您之所以会这样做,是因为索引签名强制所有属性匹配它们的返回类型.如 Typescript 文档所述:https://www.typescriptlang.org/docs/handbook/接口.html

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

虽然字符串索引签名是描述字典模式的一种强大方式,但它们也强制所有属性匹配它们的返回类型.

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.

你也可以厚脸皮,走捷径,简单地使用联合类型.所以代替 [key:string]: number 你做 [key:string]: number |字符串.

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.

这篇关于如何在 TypeScript 中为具有动态属性的对象定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆