TypeScript offers a convenient way to define class members directly in the constructor by adding visibility modifiers to the constructor parameters.
class Person { // name is a private member variable public constructor(private name: string) {} public getName(): string { return this.name; } } const person = new Person(“Jane”); console.log(person.getName()); |
Similar to arrays, the readonly keyword can be used to prevent class members from being modified.
class Person { private readonly name: string; public constructor(name: string) { // name cannot be changed after this initial definition, which has to be either at it’s declaration or in the constructor. this.name = name; } public getName(): string { return this.name; } } const person = new Person(“Jane”); console.log(person.getName()); |
Interfaces (discussed here) can define the type that a class must adhere to using the implements
keyword.
interface Shape { getArea: () => number; } class Rectangle implements Shape { public constructor(protected readonly width: number, protected readonly height: number) {} public getArea(): number { return this.width * this.height; } } |
A class can implement multiple interfaces by listing them after implements, separated by commas, like this: class Rectangle implements Shape, Colored. |