Constructor Parameter Properties
What you'll learn: How to declare and initialize class properties directly in the constructor signature using access modifiers.
The Repetitive Pattern
In TypeScript classes, you often write properties at the top of your class and then assign constructor parameters to them. This creates a lot of boilerplate:
class User {
public name: string;
public email: string;
private password: string;
constructor(name: string, email: string, password: string) {
this.name = name;
this.email = email;
this.password = password;
}
}
That's six lines just to set up three properties!
The Shorthand Solution
TypeScript offers constructor parameter properties: by adding an access modifier (public, private, protected, or readonly) to a constructor parameter, TypeScript automatically creates the property and assigns the value in one step:
class User {
constructor(
public name: string,
public email: string,
private password: string
) {
// Properties are automatically declared and initialized!
}
}
Both examples create the exact same class — same properties, same visibility, same initialization. The second version just eliminates the redundant declarations.
How It Works
Think of it like ordering furniture: the traditional way requires you to select items, pay for them, and arrange delivery in separate steps. Constructor parameter properties are like a "bundle and deliver" option — adding public, private, protected, or readonly tells TypeScript to do all the steps at once.
You can mix parameter properties with regular parameters, too:
class Product {
constructor(
public id: number,
public name: string,
category: string // Regular parameter, not a property
) {
console.log(`Creating ${name} in ${category}`);
}
}
Key Takeaway: Constructor parameter properties eliminate boilerplate by declaring and initializing class properties directly in the constructor signature when you prefix parameters with public, private, protected, or readonly.