Parameter properties
- TypeScript course
- Intermediate
- Lesson 9/89
- 4 min
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; // errorShorthand 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) {}
}Practice 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.
Starter code
// User sınıfı tanımla (public name, private age)
// constructor ile her ikisini al, this ile ata
// yeni User oluştur, name'i yazdırSample 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);Expected output
Ada
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens when you write constructor(public name: string)?
- Only a parameter is defined
- The name field is auto-created and becomes public Correct answer
- name becomes private
- The class gives an error
Explanation: 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.
2 Complete the public modifier
class User {
____ name: string;
constructor(name: string) {
this.name = name;
}
}
class User {
public name: string;
constructor(name: string) {
this.name = name;
}
}
Explanation: You write public so that the name field is accessible everywhere. private restricts to the class, protected to subclasses, and static moves to the class level.
3 Parameter property parts
| Term | Meaning |
|---|---|
constructor(public name: string) |
Public parameter property |
constructor(private age: number) |
Private parameter property |
constructor(protected id: string) |
Protected parameter property |
{} |
Shorthand (empty body) |