Can a function be created that utilizes keyof
to access an object's property, with TypeScript inferring the return value?
interface Example {
name: string;
handles: number;
}
function get(n: keyof Example) {
const x: Example = {name: 'House', handles: 8};
return x[n];
}
function put(value: string) {
}
put(get("name"));
// ^^^ Error: Argument of type 'string | number' is not assignable to parameter of type 'string'
TypeScript is merging all the allowed types together, but when the function is called with the value "name"
it does not infer the type is string
.
The issue can be resolved by casting the type.
put(get("name") as string);
Is there an alternative method to avoid using casting?