rogergl
rogergl

Reputation: 3781

How to make sure that I only can assign to fields of type array?

I have the following type definition:

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

That I use like this:

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

What I would like is to define the type in a away that the field property can only contain names of properties that are of type array ?

Upvotes: 1

Views: 38

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250136

You can use mapped types and conditional types to filter the keys of a type based on field type:

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")[]

Upvotes: 1

Related Questions