Denis Giffeler
Denis Giffeler

Reputation: 1509

How to access a specific property as a parameter in TypeScript?

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

Answers (1)

thedude
thedude

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

Related Questions