Search code examples
typescriptgenericsinterfacetyping

Typescript Pick<> using types rather than keys


I under stand how the pick type works in typescript. How ever I want a version of it that will pick all the strings out of an interface rather than using the keys.

interface Nested {
    bla: string;
    other: number;
}

interface Testing {
    bla: string;
    other: number;
    list: Array<string>;
    list2: Array<string>;
    list3: Array<any>;
    list4: Array<number>;
    objecter: Nested
    objecter2: object
}


type NewPickType<T,Type> = // Some Typescript interface Logic 

type StringArrayOnlyType = NewPickType<Testing,Array<string>>

let obj: StringArrayOnlyType = {
    bla: "", // error
    other: 0, // error
    list: [""], // ok 
    list2: [""], // ok
    list3: [""], // ok
    list4: [0], // error
    objecter: { bla: "", other: 0 }, // error
    objecter2: {} // error
}

Any ideas on how to build the NewPickType


Solution

  • Ended up figuring it out just after posting but this might help some other people.

    export type PickTypeKeys<Obj, Type, T extends keyof Obj = keyof Obj> = ({ [P in keyof Obj]: Obj[P] extends Type ? P : never })[T];
    
    export type PickType<T, Type> = Pick<T, PickTypeKeys<T, Type>>
    export type OmitType<T, Type> = Omit<T, PickTypeKeys<T, Type>>
    

    Needed to use two steps on to get they keys of the type I was looking for and one to filter the object using those keys.

    Example