根据同级值的类型设置类型

时间:2019-02-22 20:04:28

标签: typescript

我有这样的代码:

interface Entity{
    value : number | string;
}
interface Abc{
    entity: Entity;
    entityValues : number[] | string[] // <----- I want to change this type
}

即使我具有类型编号的实体对象,实体值也可以是string[]number[]。由于已经设置了实体,因此我希望也可以动态确定entityValues。

1 个答案:

答案 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"] 

};

另请参阅:https://stackoverflow.com/a/53996824/135978