TypeScript
Parameter properties
Learn the shorthand in constructor parameters.
Parameter properties
A parameter property defines and assigns a field in shorthand via the modifier in the constructor parameter. When you write constructor(public name: string), the name field is created automatically, becomes public, and is assigned the parameter value; you do not need to write this.name = name in the body.
class User {
constructor(public name: string, private age: number) {}
}
const u = new User("Ada", 30);
console.log(u.name);
// u.age; // error
Shorthand vs long form
Let's compare the same class in long form and shorthand. The shorthand removes the field declaration and the this assignment thanks to the modifier in the constructor parameter. The long form declares the field explicitly and assigns it with this in the constructor body.
// Long form:
class User1 {
public name: string;
constructor(name: string) {
this.name = name;
}
}
// Shorthand:
class User2 {
constructor(public name: string) {}
}
Exercise Write a User class
Define a User class: explicitly declare public name: string and private age: number fields. Add a constructor that takes name and age parameters and assigns them with this. Create a new User("Ada", 30) and print the name field.
Show example solution
class User {
public name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
const u = new User("Ada", 30);
console.log(u.name);
Test yourself
-
What happens when you write constructor(public name: string)?
- Only a parameter is defined
- The name field is auto-created and becomes public
- name becomes private
- The class gives an error
Show answer
The name field is auto-created and becomes public — A parameter property auto-defines and assigns the field via the modifier in the constructor parameter. public name creates an automatic public field; you do not need to write this.name = name.
-
Complete the public modifier
class User {
____ name: string;
constructor(name: string) {
this.name = name;
}
}
Show answer
class User {
public name: string;
constructor(name: string) {
this.name = name;
}
}
-
Parameter property parts
- constructor(public name: string)
- Public parameter property
- constructor(private age: number)
- Private parameter property
- constructor(protected id: string)
- Protected parameter property
- {}
- Shorthand (empty body)
Next lesson: Summary - Access modifiers