- Learning TypeScript 2.x
- Remo H. Jansen
- 135字
- 2025-04-04 17:02:05
Parameter properties
In TypeScript, when we declare a class, we can define its properties and initialize some or all of the properties using the class constructor:
class Vector { private x: number; private y: number; public constructor(x: number, y: number) { this.x = x; this.y = y; } }
However, we can use an alternative syntax, which allows us to declare the properties and initialize them using the class constructor in a less verbose way. We only need to remove the property declarations and its initialization, and add access modifiers to the arguments of the constructor of the class.
The preceding code snippet declares a class with an identical behavior to the following class. However, it uses the parameter properties syntax:
class Vector { public constructor( private x: number, private y: number ) {} }