typescript - 如何在列表中键入具有属性的对象

标签 typescript

我们的应用程序中有一些实体。每个实体都是一个特定的类型。例如我们有:

export class Tree {
  constructor(public size: number, public name: string) {}
}

export class Animal {
  constructor(public region: string, public name: string) {}
}

我们正在为我们的应用创建全局搜索,以便我们可以搜索任何实体。

我们的后端返回一个包含以下示例的列表:

{
  total: 3,
  Tree: [{ some tree data here }],
  Animal: [{ some animal data here}]
}

我想在前端的 typescript 中输入这个结果对象,但我很难让它工作:如何指示我的 SearchResult 可以有未知数量的“实体类型”,每个实体类型包含一个数组这些实体?

我尝试定义一个列出所有可能实体的类型:

export type Entities = 'Tree' | 'Animal';

然后尝试将其用作新类型的键:

export type SearchResults = {
  total: number;
  [K in Entities]: any[];
}

但它会触发如下错误:

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.

而且我无法使用 K 来恢复我的 Tree[]Animal[] 类值,而不是 any[].

最佳答案

问题不在于您的方法,而在于 类型 SearchResults 的定义。您无法向映射类型定义添加其他成员。因此,要纠正错误,请使用交集

export type SearchResults = {
  [K in Entities]: any[];
} &
{ total: number; }

documentation 。向下滚动,您会看到确切的答案

关于typescript - 如何在列表中键入具有属性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56998448/

相关文章:

javascript - 将 int 插入 String 数组

javascript - vscode - 用 node_modules 定义替换 typescript 定义

Angular 2(或 4)对象序列化

javascript - Angular 2 动态表单 - 实现清晰的功能

node.js - BigNumber 的 TypeScript 类型定义

asp.net-mvc-4 - 如何编辑 Typescript 1.4 "specified task executable location"?

javascript - Ionic 2 中的本地存储无法访问 then() 方法之外的数据

英雄 Angular 之旅 : Why is one assigned with colon and another by equal signs

angular - 发生错误 InvalidPipeArgument Angular 6

angular - md-input-container 必须包含 mdInput 指令?