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?
CodePudding user response:
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">