typescript - 如何在 TypeScript 中为具有动态属性的对象定义类型

标签 typescript typescript-typings

我有一个对象,它的 title 是字符串,order 是数字,然后上面会有动态数字类型的属性

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

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

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

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

我得到了 ts 错误

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/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.

索引签名明确表示“每当此对象使用此类型的值进行索引时,它将返回该类型的值”。

在你的例子中,你的索引签名说“只要这个对象被一个字符串索引,它就会返回一个数字”。但是,编译器发现此规则可能会被破坏,因为您的其中一个属性不是数字,因此会抛出错误。

我不确定你的问题空间是什么,但如果动态属性都有一些共同点,那么创建一个接口(interface)来抽象它们的共同点可能会更容易。不过,您如何使用所述界面实际上取决于您想要做什么。

编辑:您也可以厚颜无耻地走捷径,只使用 Union 类型。因此,您可以使用 [key:string]: number | 而不是 [key:string]: number字符串.

关于typescript - 如何在 TypeScript 中为具有动态属性的对象定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53090630/

相关文章:

Angular 2 : error TS2307: Cannot find module 'socket.io-client'

JavaScript ES6 - 计算对象数组的重复项

typescript - 预期有 2 个参数,但得到 1.ts(2554) core.d.ts(8064, 47) : An argument for 'opts' was not provided

javascript - 在 Angular 应用程序上将 XML RSS feed 转换为 Json

typescript - 如何将 typescript npm 模块导入语法转换为 ECMA2015 模块导入语法

javascript - typescript 推断函数参数联合

typescript - <promise void> typescript

typescript - 从 QuerySnapshot 获取数据

typescript - 在 TypeScript 中定义一个空对象类型

typescript - Typescript能够执行简单的功能组合吗?