

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Private Class Members
incomplete
3: TypeScript Public and Private
incomplete
4: Protected Data Members
incomplete
5: Abstract Classes and Methods
incomplete
6: Classes Implement Interfaces
incomplete
7: Classes vs. Interfaces and Types
incomplete
8: The 'this' Type
incomplete
9: Parameter Properties
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
TypeScript has a neat shorthand feature called parameter properties that allows you to declare and initialize class properties directly in the constructor parameters. This eliminates the need to separately declare properties and then assign them in the constructor body.
Normally, you'd write a class like this:
class Hero {
name: string;
health: number;
private level: number;
constructor(name: string, health: number, level: number) {
this.name = name;
this.health = health;
this.level = level;
}
}
With parameter properties, you can achieve the same result with much less code:
class Hero {
constructor(
public name: string,
public health: number,
private level: number,
) {}
}
In the example above, the constructor body {} is intentionally empty because parameter properties handle declaration and initialization. Other class methods should be defined in the class body, outside the constructor.
By adding an access modifier (public, private, protected, or readonly) to a constructor parameter, TypeScript automatically:
Parameter properties work with TypeScript's private keyword, but not with JavaScript's # private field syntax. If you need truly private fields using the # syntax, you must declare them separately:
class Hero {
#secretPower: string;
constructor(
public name: string,
secretPower: string,
) {
this.#secretPower = secretPower;
}
}
We're building an ExecutiveMember class for our premium customers. Use parameter properties to make the code more concise.