Careeroza
Classes and Objects
Declaring a Class
A class is a blueprint for objects. In TypeScript you declare each property with its type. With strict mode every property must be initialised (in the declaration or in the constructor).
Example
class Product {
name: string;
price: number;
stock = 0; // type inferred as number
constructor(name: string, price: number) {
this.name = name;
this.price = price;
}
}
const p1 = new Product("Desk Lamp", 899);
p1.stock = 25;
const p2 = new Product("Notebook", 60);
console.log(p1);
console.log(p2.name, p2.stock);Output
Product { name: 'Desk Lamp', price: 899, stock: 25 }
Notebook 0Uninitialised Property
Example
With strictPropertyInitialization (part of strict) a property that is never set is error TS2564.
class Product {
name: string;
price: number;
constructor(name: string) {
this.name = name;
}
}Compiler output (tsc)
Line 3: error TS2564: Property 'price' has no initializer and is not definitely assigned in the constructor.