Auto-accessors in TypeScript

typescript1 min

byLucas Santos

This page was machine translated. Read original / Suggest a fix

TypeScript has a bunch of really interesting features that few people know about, one of them is auto-accessors in classes.

Available since TypeScript 4.9, it’s also a feature described in the original decorators proposal.We’ve actually talked about decorators here.

So here’s how it works. When you have an accessor, you typically have a get method that retrieves an internal class variable. For example:

class Pessoa {
#__nome: string;
get name() {
return this.#__nome;
}
set name(val: string) {
this.#__nome = val;
}
constructor(nome: string) {
this.nome = nome;
}
}

See how that’s not one or two lines, but seven just to create an accessor that sets and gets the internal #__nome variable? It would be so much better if you could do all that at once, and that’s exactly what auto-accessors are for. All that code I just wrote can become this:

class Person {
accessor nome: string;
constructor(nome: string) {
this.nome = nome;
}
}

Under the hood, auto-accessors do exactly what we did in that first example. They expand nome into an internal private variable and an external variable you can only access through a getter and a setter.

All in all, this feature isn’t about logic, it’s about quality of life. Especially when you’re creating decorators that need a bunch of getters and setters.