Search code examples
javascripttypescriptanonymous-functioninstance-variables

Typescript - Class Instance Variable As An Accessor To The First Value In A Set


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?


Solution

  • 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