TypeScript constructor parameter properties

For those with an OOP background, you'll often find yourself instantiating a new object by passing one or more values via the constructor and then setting them as object properties, like so:
class User {
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
}
const user = new User("John", "Doe");
console.log(`${user.firstName} ${user.lastName}`); // John Doe
There's absolutely nothing wrong with this approach, however, I often say that the best programmers are the laziest ones*. Did you know you can define the class properties in line with the constructor definition? The following code sample is functionally equivalent to the first.
class User {
constructor(public firstName: string, public lastName: string) {}
}
const user = new User("John", "Doe");
console.log(`${user.firstName} ${user.lastName}`); // John Doe
You may also modify the parameter scope by using protected and private keywords, as well as marking the property as readonly.
class Account {
constructor(public emailAddress: string, private readonly password: string) {}
}
const account = new Account("john.doe@example.com", "hunter2");
console.log(account.emailAddress); // john.doe@example.com
// Property 'password' is private and only accessible within class 'Account'
console.log(account.password);
*From an automation perspective, not from a "don't write tests" view!




