TamerB
TamerB

Reputation: 1441

How to convert a string to a string property

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

Answers (1)

Nitzan Tomer
Nitzan Tomer

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

(code in playground)


Edit

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

Related Questions