OOP with TypeScript


OOP with TypeScript

1. property type

Unlike JS, properties in a class must have type. You can omit the constructor to init the class with undefined to every property.

class User {
  firstName:string;
  lastName:string;
  email: string;
}

A constructor is recommanded:

class User {
  firstName:string;
  lastName:string;
  email: string;

  constructor(firstName:string, lastName:string,email:string){
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
  }
}

notice that inside the () of constructor, every prams needs a type.

2. method type

A method of class also can have type when a return statement is needed. It defines the type of return when the method is being called.

class User {
  firstName:string;
  lastName:string;
  email: string;

  emailCheck(email:string):boolean {
    return email===this.email;
  }
}

notice that the email pram type is string but the function returns a boolean.

use get (getter)

getters and setters are properties that use some logic to return a value.

class User {
  firstName:string;
  lastName:string;
  email: string;

  get fullName():string {
    return `${this.firstName} ${this.lastName}`;
  }

}

User.fullName will return a string combining first name and last name.

use set (setter)

A private property is being use here:

class User {
  firstName:string;
  lastName:string;
  email: string;
  private _isAdmin: boolean;

  set isAdmin(value:boolean) {
    this._isAdmin = value;
  }

  get isAdmin():boolean {
    return this._isAdmin;
  }
}

So now we can set whether a user is admin or not.