TypeScript Parameter Properties Tutorial
In this TypeScript tutorial we learn how to use parameter properties with the constructor, to simplify our property declarations.
Parameter Properties
Parameter properties allow us to use the constructor to simplify our property declarations.
We can add an access modifier in front of a parameter in the constructor, and this will tell the compiler to initialize the value.
class ClassName {
constructor(access-modifier property: type) {}
}
To demonstrate, let’s use our example from the previous lesson and add public public for the id property, and private private for the name.
class Employee {
readonly id: number
private name: string
nickname?: string
constructor(public id: number, private name: string) {
this.id = id
this.name = name
}
walk(): void {
console.log(this.name + 'is walking...')
}
}
let emp1 = new Employee(0, 'John')
Because parameter properties are initialized, we an remove the declarations above the constructor, as well as everything in the constructor body.
class Employee {
nickname?: string
constructor(public id: number, private name: string) {}
walk(): void {
console.log(this.name + "is walking...")
}
}
let emp1 = new Employee(0, 'John')
Basically, we declare all our properties in the constructor’s parameter list. So we can bring the nickname down as well.
And if you remember, we had our id as readonly , so we’ll add that. And by convention we add an underscore to private properties.
We’ll also break up the parameter list to have each declaration on its own line so it’s easier to read.
class Employee {
constructor(
public readonly id: number,
private name: string,
public nickname?: string
) {}
walk(): void {
console.log(this.name + "is walking...")
}
}
let emp1 = new Employee(0, 'John')
Summary: Points to remember
- Parameter properties allow us to simplify our property declarations.
- To initialize a property, we add an access modifier to it in the constructor’s parameter list.
- Because parameter properties are automatically initialized, we don’t need to declare them or initialize them in the constructor.