我们的应用程序中有一些实体。每个实体都是一个特定的类型。例如我们有:
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/