I have an Mapped Type, and want to implement a function which receive params as the key of MappedType, return the MappedType of key, however the code occurs an error.
type MappedType = {
a: {
a: string;
};
b: {
b: number;
}
};
function getValue<T extends keyof MappedType>(key: T): MappedType[T] | undefined {
if (key === 'a') {
// here get error
// Type '{ a: string; }' is not assignable to type 'MappedType[T]'.
// Type '{ a: string; }' is not assignable to type '{ a: string; } & { b: number; }'.
// Property 'b' is missing in type '{ a: string; }' but required in type '{ b: number; }'.
return {
a: '2'
};
}
return;
}
how to infer the type successfully?
New contributor
熊俊文 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.