Constructor Shorthand
Declare and assign class fields directly in the constructor parameters.
Syntax
constructor(public name: string) {}TypeScript offers a shortcut: put an access modifier in front of a constructor parameter and it automatically becomes a class field, assigned for you.
This removes the repetitive pattern of declaring a field and then writing this.x = x.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A small DTO class uses constructor shorthand to declare and assign four fields in a single concise constructor.
- A value object is defined with readonly constructor shorthand parameters so the fields are immutable after creation.
- A service class injects its dependencies as private constructor parameters using shorthand to reduce boilerplate.
More examples
Constructor shorthand basics
Uses constructor parameter shorthand to declare and initialise x and y as public properties without property declarations.
class Point {
constructor(
public x: number,
public y: number,
) {}
}
const p = new Point(3, 4);
console.log(p.x, p.y); // 3 4Readonly shorthand properties
Combines constructor shorthand with readonly to create an immutable value object with minimal syntax.
class Money {
constructor(
public readonly amount: number,
public readonly currency: string,
) {}
toString(): string {
return `${this.amount} ${this.currency}`;
}
}
const price = new Money(9.99, 'USD');
// price.amount = 10; // Error: readonlyMixed shorthand and logic
Mixes shorthand private parameters with a non-shorthand property that requires initialisation logic in the constructor body.
class Logger {
private readonly timestamp: Date;
constructor(
private readonly prefix: string,
private readonly level: string = 'info',
) {
this.timestamp = new Date();
}
log(message: string): void {
console.log(`[${this.level}] ${this.prefix}: ${message}`);
}
}
Discussion