我有这样的代码:
interface Entity{
value : number | string;
}
interface Abc{
entity: Entity;
entityValues : number[] | string[] // <----- I want to change this type
}
即使我具有类型编号的实体对象,实体值也可以是string[]
或number[]
。由于已经设置了实体,因此我希望也可以动态确定entityValues。
答案 0 :(得分:1)
您似乎想要的是将entityValues
字段设为a的方法:
// Distribute the types of a union across arrays
// This gets us `string[] | number[]` instead of `(string | number)[]`
// If you want to store the values of _all_ the fields, instead of fields of a single type
// simply use `Entity[EntityFields][]` for `entityValues`
// See https://stackoverflow.com/a/53996824/135978 for more information
type HomogenousArray<T> = T extends unknown ? T[] : never;
interface Abc<Entity, EntityFields extends keyof Entity = keyof Entity> {
entity: Entity,
// Values of a particularly typed sub-section of your entity's fields
entityValues: HomogenousArray<Entity[EntityFields]>
// Values of any or all of your entity's fields
anyEntityValues: Entity[EntityFields][]
}
用法非常简单:
interface Entity {
id: number,
value: string
}
type Z = Abc<Entity>;
const z: Z = {
entity: {id: 1, value: "hi"},
entityValues: [1, 2, 3],
// ["strings", ""] will also work
// ["strings", 123] will *not* work
anyEntityValues: [1, "mixed types", 2, "work here"]
};