0

I have function written in typescript where i am passing the object and key as an input parameter and in function return i am expecting the object with key value pair:

const article = {
    id: 1,
    title: "TypeScript Explained",
    active: true,
    getSlug: () => 'typescript-explained',
};

type Pick<T, U extends keyof T> = { [K in U]: T[K] };

function pick<T,U extends keyof T>(obj:T,key:U):Pick<T,U>{
    return  {[key]: obj[key]}
}
pick(article,'title')

But on calling the function i am getting the error like Type '{ [x: string]: T[U]; }' is not assignable to type 'Pick<T, U>'.

Can someone help?

1
  • Please format the question so we can read it properly Commented Jan 31, 2023 at 16:12

1 Answer 1

1

Typescript infers that type of {[key]: obj[key]} is { [x: string]: T[U]; }.

Thats why it panics when you try to return it as Pick<T,U>

You can either let it infer return type:

 function pick<T, U extends keyof T>(obj: T, key: U) {
    return { [key]: obj[key] };
  }

then function returns { [x: string]: T[U]; }

or explicitly set type of {[key]: obj[key]} with as:

 function pick<T, U extends keyof T>(obj: T, key: U): Pick<T, U> {
    return { [key]: obj[key] } as Pick<T, U>;
  }

then function returns value of type

Pick<{
    id: number;
    title: string;
    active: boolean;
    getSlug: () => string;
}, "title">
Sign up to request clarification or add additional context in comments.

4 Comments

what about function pick<T, U extends keyof T>(obj: T, key: U): Partial<T> { return { [key]: obj[key] } as T; } ?
@VinayakVohra Result type is: Partial<{ id: number; title: string; active: boolean; getSlug: () => string; }> since T is typeof obj
Yes, that seems to be working. Thank you. But when i already defined key as Union of keys(with keyof operator) from the object then why its treating it as 'string' rather than a object key.
@ramahuja Second argument of pick() has typeof "id" | "title" | ... <all keys of first argument as strings> so typeof key will be string since you can pick any of available strings I think

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.