You write a class with the class keyword, as in JavaScript, and add types to its fields, constructor parameters and methods. Under strict mode, TypeScript also reports a field that is declared but never set, by an initializer or in the constructor.
class Person {
private _id: number;
protected name: string;
public email: string;
constructor(id: number, name: string, email: string) {
this._id = id;
this.name = name;
this.email = email;
}
public greet(): string {
return `Hello, I'm ${this.name}`;
}
protected getId(): number {
return this._id;
}
}
Members can carry the public, protected or private access modifiers, and public is the default.
Parameter properties shorten the common case. constructor(private id: number) {} declares the field and assigns it in one step.
A class can inherit from one base class with extends, and promise to match any number of interfaces with implements.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓