Show List
TypeScript Classes
TypeScript allows to add type and access modifiers to the class properties and methods. There are three main access modifiers:
- public - can be accessed from anywhere
- private - can be accessed only from within the class
- protected - can be accessed from within the class or from inherited classes
Below is a JavaScript class example:
class Person {personName;constructor(nm) {this.personName = nm;}getName() {return this.personName;}printName() {console.log(this.personName);}}let john = new Person("John Miller");john.printName();
This class can be written in TypeScript as below specifying the types and access modifiers:
myFunction.ts
class Person {private personName: string;constructor(nm: string) {this.personName = nm;}public getName(): string {return this.personName;}public printName(): void {console.log(this.personName);}}let john = new Person("John Miller");john.printName();
Output:
PS C:\Users\mail2\Downloads\demo> tsc myFunction.ts PS C:\Users\mail2\Downloads\demo> node myFunction.js John Miller
Leave a Comment