Constructor Inputs
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 8 of 24.
A constructor runs when an instance is created. Its arguments provide values that the object will need later. TypeScript can store an argument on the instance automatically.
class Price {
constructor(private readonly tax: number) {}
total(amount: number) { return amount * (1 + this.tax); }
}
const price = new Price(0.2);
price.total(10); // 12private makes the field accessible only inside the class. readonly prevents assigning a different value after construction; it does not freeze a referenced object. Together, these words before a constructor parameter create and initialize this.tax. No second assignment is needed. Nest uses this shorthand to keep objects it supplies to a controller.
Challenge
EasyIn src/exercise.ts, add a constructor to Label. It receives a string prefix and stores it using TypeScript’s private readonly parameter shorthand. Keep render unchanged.
Try it: GET /result returns ["Note: Read","Task: Write"]. Each instance keeps the prefix passed at construction.
Try it yourself
export class Label {
// Add a constructor that stores the supplied prefix.
render(text: string) {
return this.prefix + text;
}
}
All lessons in TypeScript and NestJS
Practice on your own: Express playground