TypeScript Reference ยท Classes, Enums and Decorators
TypeScript parameter properties
Reference for TypeScript parameter properties: declare and assign class fields from constructor parameters with public, private, protected or readonly.
A parameter property is a constructor parameter prefixed with an access modifier or readonly. TypeScript declares a field with the same name and type and assigns the argument to it, so you do not write the field and the this.x = x line yourself.
It is the shortest way to write small classes that mostly store their constructor arguments. The shorthand is a TypeScript feature that produces ordinary assignments in the emitted JavaScript.
class Money { constructor(public readonly amount: number, private currency: string) {} }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
constructor([modifier] name[?]: Type [= default], ...)
| Modifier | Effect |
|---|---|
public |
Public field. |
protected |
Visible in the class and subclasses. |
private |
Visible only in the class (compile-time check). |
readonly |
Assignable only in the constructor; can be combined with the others (public readonly). |
override |
Marks that the field overrides a base-class member (needs a base class). |
Edge cases:
- Rest parameters and destructured parameters cannot be parameter properties.
- Parameter properties are assigned first, before other statements in the constructor body; in a derived class they come right after
super(). erasableSyntaxOnly(and Node's built-in type stripping) reject parameter properties, because they need code generation. Use explicit fields in that setting.privatehere is TypeScript-only. For real runtime privacy declare a#fieldexplicitly.
Usage notes
- Do not declare the same name again as a normal field; TypeScript reports a duplicate identifier.
- The shorthand shines for data holders and dependency injection, where every argument becomes a field.
- A modifier-free parameter is just a parameter. Only the modifier makes it a property, a detail that is easy to miss during review.
- Validate or transform arguments in the body when needed; the field already holds the raw value by then.
- Because the field exists on every instance, parameter properties show up in
JSON.stringifyandObject.keys(includingprivateones).
Related
- Class fields, Constructors, Private fields
- Lessons: Classes, Access modifiers