Classes
Classes as blueprints: fields, methods, and creating instances.
14 minLevel 3 of 20
Classes as blueprints
A class describes the shape and behavior of objects you will create. The class is the blueprint; each new ClassName() produces an instance.
Nest decorators (@Injectable(), @Controller()) attach metadata to classes so the framework knows how to use them.
Define and instantiate
class Product {
constructor(public sku: string, public price: number) {}
label() { return `${this.sku}: $${this.price}`; }
}
const p1 = new Product("BOOK-1", 29);
const p2 = new Product("BOOK-2", 39);
console.log(p1.label());
console.log(p2.label());
console.log("same class?", p1.constructor === p2.constructor);Fields and methods
Instance fields hold state. Methods use this to read/write that state. TypeScript also supports parameter properties in the constructor — Nest services use this constantly.
Parameter properties
class UsersService {
constructor(private readonly repo: { find(): string[] }) {}
list() { return this.repo.find(); }
}
console.log(new UsersService({ find: () => ["a", "b"] }).list());Prototype link
Methods live on the prototype and are shared by instances. Each instance has its own field values. Open the Object Lifecycle simulator to see allocation step by step.
Shared methods
class Counter {
n = 0;
inc() { this.n++; return this.n; }
}
const c1 = new Counter();
const c2 = new Counter();
console.log(c1.inc(), c1.inc());
console.log(c2.inc());
console.log("same method fn?", c1.inc === c2.inc);Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice