Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access Object property in Typescript

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>’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone help?

>Solution :

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">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading