Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading