Skip to content Skip to sidebar Skip to footer

Typescript Generic Type For "pick" Function (result Object Values Types)

Have problem writing type for pick function. Everything works fine while picking only one key or several keys with values of same type. But if I'm trying to pick few keys and their

Solution 1:

You have an error in your mapped type you probably want to use O[K] instead of O[T] so you end up with { [K in T]: O[K] }. You want the type for each key K, not the type of all properties in the T union.

Also I would use Pick since Pick is homomorphic and would preserve modifiers such as readonly and optional.

Also obj?: never probably does not do what you want it to do, anything is assignable to never, you are better off omitting the parameter in that overload:

export function pick<O,T extends keyof O>(keys:T[], obj?: O): Pick<O,T>;
export function pick<T>(keys:T[]): Mapper;
export function pick<O,T extends keyof O>(keys:T[], obj?: O){//....
}

Playground Link

Post a Comment for "Typescript Generic Type For "pick" Function (result Object Values Types)"