Auto implemented properties in TypeScript
When working with classes in TypeScript, if the class has some properties and if you want to initialize these properties, you would do it in the constructor.
The traditional way
For instance, let’s say, we have a User
class and there are some properties that we want to initialize, here’s how we can do it.
class User {
id: number;
name: string;
sex: string;
constructor(id: number, name: string, sex: string) {
this.id = id;
this.name = name;
this.sex = sex;
}
}
const user = new User(1, 'Cherika', 'F');
console.log(user.name); // Cherika
As you can tell, to initialize a class property, you can use the constructor as a single source of truth.
Now, this works perfectly fine but if you can see, there’s a lot of duplication going on here.
First, we declared the properties in the class and then all these properties get initialized through constructor parameters under its body using this
.
But guess what? There’s a more concise way of doing so.
Auto implemented properties
Auto implemented properties or parameter properties is a way of turning constructor properties into class properties with the same name and value.
So, if want to write the previous example with this syntax, here’s how we can do it.
class User {
constructor(
public id: number,
public name: string,
public sex: string
) {}
}
const user = new User(1, 'Cherika', 'F');
console.log(user.name); // Cherika
As you can tell, for this to work, it’s important to prefix constructor arguments with one of the visibility modifiers public
, private
, protected
, or readonly
explicitly.
So, if you want to keep a property as public, you need to specify public
explicitly. Same for other visibility modifiers as well.
💡 Trivia: PHP has also got a similar feature in PHP 8 called constructor property promotion recently which works exactly like auto implemented properties.
In closing
Auto implemented properties help reduce the amount of code dramatically since the declaration and assignment of the property will happen in the constructor parameters itself.
So, unless you’re not doing any sort of calculation before doing the assignment, using the parameter properties is a way to go, in my opinion.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.