0

In a typescript class, are you able to specify an instance variable as a shortcut to access the first value in a Set?

What I want to do is something like this:

export class Car {
    public gears: Set<string>;
    public gear: string => gears?.values().next().value; // doesn't work

    constructor() {
        gears = new Set<string>(["N", "First", "Second", "Third", "Fourth"]);
    }
}

Usage:

var car = new Car();
console.log(car.gear); // => "N"

I know you can do it with a function like

public gear = (): string => gears?.values().next().value;

But when you call that you need to call it as a function instead of an instance variable

var car = new Car();
console.log(car.gear()); // => "N"

While that works, it's not ideal because semantically it doesn't make a lot of sense that gear is a function.

Is what I'm asking possible in Typescript?

1
  • 1
    You're looking for "getter" Commented Aug 15, 2022 at 19:12

1 Answer 1

1

You're looking for a getter :

export class Car {
    public gears: Set<string>;
    public get gear(): string {
        return this.gears.values().next().value
    }

    constructor() {
        this.gears = new Set<string>(["N", "First", "Second", "Third", "Fourth"]);
    }
}

Playground

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.