Course contentsShow
← TypeScript
Lesson 1024 of 1,79624. Classes in TypeScriptFree lesson

Parameter Properties Shorthand

Combine constructor parameters and property declarations using access modifiers or readonly.

Parameter Properties Shorthand

You'll learn: How to combine constructor parameters and property declarations using TypeScript's compact syntax.

The Repetitive Pattern

When building TypeScript classes, you've likely written code like this over and over:

class User {
  id: number;
  username: string;
  readonly createdAt: Date;

  constructor(id: number, username: string, createdAt: Date) {
    this.id = id;
    this.username = username;
    this.createdAt = createdAt;
  }
}

Notice the repetition? You declare each property twice: once at the class level, and again in the constructor parameter list. Then you write assignments for each. That's a lot of ceremony!

The Shorthand Solution

TypeScript offers parameter properties — a way to declare properties directly in the constructor by adding an access modifier (public, private, protected) or readonly to the parameter:

class User {
  constructor(
    public id: number,
    public username: string,
    readonly createdAt: Date
  ) {
    // No assignments needed! TypeScript handles it automatically.
  }
}

const user = new User(1, "alice", new Date());
console.log(user.username); // "alice"

The compiler automatically creates properties and assigns the constructor arguments to them. Much cleaner!

How It Works

Think of it like ordering a custom sandwich: instead of saying "bread, then lettuce, then add the lettuce to the bread, then tomato, then add the tomato..." you just point at ingredients and say "include this." TypeScript understands the intent.

Adding public, private, protected, or readonly transforms a parameter into a full class property:

class Account {
  constructor(
    public accountNumber: string,
    private balance: number,
    protected readonly type: string
  ) {}
  
  getBalance() {
    return this.balance; // Private property accessible inside
  }
}

Mixing Styles

You can combine parameter properties with traditional properties:

class Product {
  description: string = "No description"; // Regular property

  constructor(
    public id: number,
    readonly name: string
  ) {}
}

Key Takeaway: Use access modifiers or readonly on constructor parameters to automatically create and initialize class properties, eliminating repetitive declaration and assignment code.