Is it feasible to create a function that maintains typing and functions in the same way as this:
class Example {
someNumber:number = 1;
someString:string = "test";
}
const example = new Example();
const value = example.someNumber; // type = number
I am interested in developing a function like this:
function getValueFromInstance<T>( target:T, key:keyof T ) {
return target[ key ];
}
const value = getValueFromInstance( example, "someNumber" ); // type = string | number
TypeScript is able to determine that the possible outcome can only be a string
or a number
at this point. Is there a way to take it a step further and differentiate between the two? Especially if "someNumber"
is hardcoded in the code rather than being fetched from a variable?