0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.