Class Types
In TypeScript, a class is a blueprint for creating objects with specific properties and methods. Classes can implement interfaces, which define the structure that the class must adhere to.
Simple class example
class Video {
title: string = '';
private _year: number = 0; // `private` keyword is specific to TypeScript
// and fails at COMPILE TIME if accessed directly.
// Use getter and setter to access this property.
#myPrivateRating: number = 5; // `#` prefix is specific to JavaScript
// and fails at RUNTIME if accessed directly.
// Use getter and setter to access this property.
publicRating: number = 0;
constructor(title: string) {
console.log("Constructor called");
this.title = title;
}
// Getter and Setter for the private property `_year`
// We use _year as the private property name to avoid naming conflicts with the getter and setter methods.
get year(): number {
console.log("Getter for year called");
return this._year;
}
set year(value: number) {
console.log("Setter for year called");
this._year = value;
}
printItem(): void {
console.log(`
Title: ${this.title}, \
Year: ${this.year}, \
My Private Rating: ${this.#myPrivateRating}, \
Public Rating: ${this.publicRating}
`);
}
}
let terminator = new Video("Terminator");
terminator.printItem();
// Constructor called
// Getter for year called
// Title: Terminator, Year: 0, My Private Rating: 0, Public Rating: 0
terminator.year = 1984; // calling the setter to set the year
terminator.printItem()
// Constructor called
// Setter for year called
// Getter for year called
// Title: Terminator, Year: 1984, My Private Rating: 0, Public Rating: 0
terminator.myPrivateRating = 5; // compile error Property 'myPrivateRating' does not exist on type 'Video'.
// Need to use the setter to set the private rating
terminator.publicRating = 4.5; // public property can be accessed directly
terminator.printItem();
// Constructor called
// Getter for year called
// Title: Terminator, Year: 0, My Private Rating: 0, Public Rating: 4.5
Last updated on