Reputation: 1509
A simple class is given:
class Point {
public x: number;
public y: number;
…
}
A specific property of the class should be accessed as a parameter. In JavaScript this is quickly formulated as follows:
let p = new Point();
function getXorY(xy) {
return p[xy]; // like p["x"] instead of p.x
}
console.log(getXorY("x"));
But how is this implemented in TypeScript?
I have searched thoroughly for an answer. Since I couldn't think of any suitable keywords, unfortunately without success.
On the way to a possible solution to the problem, I stumbled across "keyof" - but without getting any closer to the solution.
Please do not rate the example in terms of its usefulness.
Upvotes: 0
Views: 831
Reputation: 9814
Define getXorY
like this:
function getXorY(xy: keyof Point) {
return p[xy]
}
you'll be able to pass only 'x'
or 'y'
to it
Upvotes: 2