Sub topic 10
Parameter Properties as Constructor Shorthand
Prerequisites and the basic idea
Assume you know basic TypeScript types, JavaScript constructors, and the this keyword. A parameter property is a constructor parameter that also declares and initializes a class field.
Without a parameter property, you write the field and assignment separately:
class User {
private name: string;
constructor(name: string) {
this.name = name;
}
describe(): string {
return `User: ${this.name}`;
}
}A parameter property combines the same steps:
class User {
constructor(private name: string) {}
describe(): string {
return `User: ${this.name}`;
}
}
const user = new User("Ada");
console.log(user.describe()); // User: AdaThe private modifier tells TypeScript to create a private field named name and assign the constructor argument to it.
Choosing the modifier
A parameter property needs a visibility or field modifier. The modifier becomes part of the class field's API.
| Declaration | Meaning |
|---|---|
| `public name: string` | Any caller can read and write `name` |
| `private name: string` | Only the declaring class can access `name` |
| `protected name: string` | The class and its subclasses can access `name` |
| `readonly name: string` | The value cannot be reassigned after construction |
You can combine modifiers:
class Point {
constructor(
public readonly x: number,
public readonly y: number,
private label: string = "point"
) {}
describe(): string {
return `${this.label}(${this.x}, ${this.y})`;
}
}
const point = new Point(3, 4);
console.log(point.describe()); // point(3, 4)
console.log(point.x); // 3
// point.x = 10;
// Error: Cannot assign to 'x' because it is a read-only property.A default value works like a normal parameter default. If the caller omits the third argument, label becomes "point".
Common errors
Do not declare the same field twice:
class Product {
// private id: string;
// constructor(private id: string) {}
}The commented declaration would duplicate the parameter property. Use either the explicit field form or the shorthand, not both.
Parameter properties belong only in constructors. A regular method parameter does not create a field:
class Logger {
log(message: string): void {
console.log(message);
}
}Use private when callers should use methods instead of changing state directly. Use public readonly for values that callers may inspect but must not replace.
Exercise
Rewrite class File { private name: string; constructor(name: string) { this.name = name; } } using a parameter property.
Show answer
class File { constructor(private name: string) {} }