Sub topic 10
Parameter Properties as Constructor Shorthand
This chapter assumes you can write a TypeScript class with typed fields and a constructor, and that you know what public, private, protected, and readonly mean. It covers the shorthand that merges a field declaration, a constructor parameter, and an assignment into one place.
The repetition problem
Many constructors do nothing except copy arguments into fields. Each value is then written out three times: as a field, as a parameter, and as an assignment.
class Product {
public readonly sku: string;
private price: number;
constructor(sku: string, price: number) {
this.sku = sku;
this.price = price;
}
describe(): string {
return `${this.sku}: $${this.price.toFixed(2)}`;
}
}With two fields this is tolerable. With eight, the constructor becomes a block of boilerplate that hides the logic.
The shorthand
If you put an accessibility modifier or readonly in front of a constructor parameter, TypeScript treats it as a parameter property. It declares a field with the same name and type, and it assigns the argument to that field at the start of the constructor.
class Product {
constructor(
public readonly sku: string,
private price: number
) {}
describe(): string {
return `${this.sku}: $${this.price.toFixed(2)}`;
}
}
const product = new Product("A-100", 19.5);
console.log(product.describe()); // A-100: $19.50This class has the same fields, types, and visibility as the first version. The empty constructor body is normal, because the assignments are generated for you.
Which modifiers trigger it
| Parameter written as | Field created | Notes |
|---|---|---|
| `public x: number` | public | Readable and writable from anywhere |
| `private x: number` | private | Accessible only inside the class |
| `protected x: number` | protected | Accessible in the class and its subclasses |
| `readonly x: number` | public, readonly | Visibility defaults to public |
| `private readonly x: number` | private, readonly | Common for injected dependencies |
| `x: number` | none | An ordinary parameter |
A modifier is what makes a parameter a parameter property. Without one, the name exists only inside the constructor body.
Mixing with ordinary parameters and defaults
You can combine parameter properties, plain parameters, and default values in any order.
class Logger {
constructor(
private readonly prefix: string,
public level: "info" | "debug" = "info",
verbose: boolean = false
) {
if (verbose) {
console.log(`Logger created with prefix ${prefix}`);
}
}
log(message: string): void {
console.log(`[${this.prefix}] (${this.level}) ${message}`);
}
}
const logger = new Logger("app");
logger.log("started"); // [app] (info) startedHere prefix and level become fields. verbose does not, so writing this.verbose elsewhere in the class is a compile error. This is the most common mistake with the shorthand. If a field is missing, check whether you left out the modifier.
Parameter properties and inheritance
In a subclass, the parameter-property assignments run right after the super(...) call returns. You must call super before touching this, and a subclass with parameter properties needs a super call like any other.
class Animal {
constructor(
public readonly name: string,
protected sound: string = "..."
) {}
speak(): string {
return `${this.name} says ${this.sound}`;
}
}
class Dog extends Animal {
constructor(
name: string,
private tricks: string[] = []
) {
super(name, "woof");
}
addTrick(trick: string): void {
this.tricks.push(trick);
}
describe(): string {
return `${this.speak()} and knows ${this.tricks.length} tricks`;
}
}
const dog = new Dog("Rex");
dog.addTrick("sit");
console.log(dog.describe()); // Rex says woof and knows 1 tricksname is a plain parameter in Dog, so it is forwarded to the base class and not redeclared. If Dog wrote public name: string again, it would declare a second field with the same name as the inherited one. That is redundant and, with some modifier combinations, a type error. Use a modifier in the subclass only for values the subclass itself owns.
Restrictions and gotchas
- Parameter properties are allowed only in a constructor implementation. They are an error in overload signatures, in ordinary methods, and in declaration files.
- A parameter property cannot use destructuring.
constructor(private { a, b }: Options)is rejected, so assign from the destructured values in the body instead. - You cannot create a
#privatefield this way.constructor(#x: number)is a syntax error. Declare#xas a field and assign it in the body. - Field initializers can run before or after parameter-property assignments, depending on your compiler settings. With
useDefineForClassFieldsenabled (the default when targeting ES2022 or later), a field initializer such asupper = this.name.toUpperCase()that reads a parameter property is reported as used before its initialization. Put that logic in the constructor body. - Parameter properties generate code, so they are not purely type-level syntax. If you turn on the
erasableSyntaxOnlycompiler option (TypeScript 5.8 and later), or run TypeScript files directly with a type-stripping runtime, parameter properties are rejected. In those setups, use explicit fields.
When to use it
Parameter properties suit classes whose constructors only store their arguments. That includes dependency-injection classes with several private readonly collaborators, small value objects, and data holders.
Prefer explicit fields when:
- The class has few fields and you want the field list to stand out at the top.
- A field needs a documentation comment or a decorator. Those are easier to read on a normal declaration.
- The field is derived or transformed in the constructor and does not simply mirror an argument.
- Your team targets a runtime that strips types without compiling them.
Mixing both styles in one class works, but mixing them for the same kind of field makes a class harder to scan. Choose one style per class.
Exercise
Rewrite this class using parameter properties, keeping the same visibility and mutability. Then say what happens if you remove private from owner in your version and the method who() still returns this.owner.
class Ticket {
readonly id: number;
private owner: string;
seat: string;
constructor(id: number, owner: string, seat: string) {
this.id = id;
this.owner = owner;
this.seat = seat;
}
who(): string {
return this.owner;
}
}
Show answer
class Ticket {
constructor(
public readonly id: number,
private owner: string,
public seat: string
) {}
who(): string {
return this.owner;
}
}
If private is removed from owner, the parameter has no modifier, so it is only a local constructor parameter and no field is created. The compiler then reports that property owner does not exist on type Ticket at this.owner. Writing public owner: string or private owner: string fixes it.