author avatar

giritharan

Wed May 08 2024

Classes And Functions in Ts.
Classes:
• Ts add helps to add type annotations for the classes.


class User {
  constructor(public name: string, public age: number) {}
}
const ue = new User("github", 24); 


• In Ts we don't need to initialize the properties and values inside the constructor if we are using access modifiers in the params. TypeScript will automatically initialise and assign values to class properties.
Getters / Setters:
• Classes can also have accessors
• For the getter function we can able to set return value type but for setter function we can't.
• setter functions are always expected props.
• If a getter exists but no setter the property is automatically readonly
• If the type of the setter parameter is not specified, it is inferred from the return type of the getter
• For class props always try to use _ name convention for better maintainbility.


class User {
  private _currentCount: number = 0;
  constructor(public name: string, public age: number) {}

  get fetch_name(): string {
    return this._name;
  }

  get fetchCount(): number {
    return this._currentCount;
  }

  set increaseCount(prop: number) {
    this._currentCount = prop + this._currentCount;
    this.logData();
  }

  private logData(): void {
    console.log("Count Increased");
  }
}

const fetchUser = new User("github", 24);


Abstract:
• If classes or method are marked as abstract those are only for readonly purposes, means they can be only used as base class/sub class.
• So that reason we can't create object on the class who are marked as abstract.


abstract class Photo {
  constructor(public isCameraOn: boolean, public isFlashOn: boolean) {}
}

class Phone extends Photo {}
const ph = new Phone(true, true);


#typescript #javascript