Issue
Given the following example code:
interface Foo {
name: string;
age: number;
}
const foo: Foo = { name: 'lorem', age: 123 };
const useObject = <T>(obj: T) => {
const getValue = (key: keyof T): [RETURN HERE] => {
return obj[key];
}
return { getValue };
}
const { getValue } = useObject<Foo>(foo);
getValue('name');
What would I need to replace [RETURN HERE]
with to give an accurate return type? For example, the type of getValue('name')
would be string
and the type of getValue('age')
would be number
.
Solution
Use a generic to "store" what key
is, then use it in the return type:
const getValue = <K extends keyof T>(key: K): T[K] => {
return obj[key];
};
And as @AluanHaddad points out, for this case you don't actually need the return type to be explicitly annotated:
// automatically inferred to return T[K]
const getValue = <K extends keyof T>(key: K) => {
Answered By - catgirlkelly
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.