Reputation: 1441
I'm trying to write a function using Typescript that takes 2 arguments in which the second argument is always of type string. The function should apply the second argument on the first argument as its property
Example:
let x = measure('Hello', 'length'); // should return 'Hello'.length
// => x = 5
How can I convert the string 'length' to be a property of 'Hello' to return 'Hello'.length?
Upvotes: 0
Views: 330
Reputation: 164129
If I understood you:
function measure(obj: any, property: string): any {
return obj[property];
}
let x = measure('Hello', 'length');
console.log(x); // 5
Or even better:
function measure<T, K extends keyof T>(obj: T, property: K): T[K] {
return obj[property];
}
In this version the compiler can infer the type of the returned value, and will also enforce that only existing property names are used, for example:
let x = measure('Hello', 'lengthy'); // error
Upvotes: 3