如何确保只能分配给数组类型的字段?

时间:2018-07-10 10:09:54

标签: typescript

我具有以下类型定义:

export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

我这样使用:

let props: Array<{ p: PropertyNames;
                  field: keyof Omit<UnitOffersComponent, "offerTypes"> }> = [...];

我想在字段属性只能包含数组类型的属性名称的情况下定义类型?

1 个答案:

答案 0 :(得分:1)

您可以使用映射类型和条件类型来根据字段类型过滤类型的键:

type FieldsOfType<T, TFieldType>  = { [P in keyof T] : T[P] extends TFieldType ? P : never }[keyof T];

//Usage

interface UnitOffersComponent {
    n: number;
    numArray: number[];
    strArray: string[];
}


let props: Array<FieldsOfType<UnitOffersComponent, any[]>>; // is of type ("numArray" | "strArray")[]
相关问题