Classes, Objects, Props and Interfaces in Typescript

Get started with object oriented programming in Typescript.

Typescript behaves like a language with built-in support for OOP concepts, and does not carry the quirks of Javascript in that respect.

Classes and Objects

Define classes and objects like how you define in any of the popular OOP languages.

class Fruit {
  public name: string;
  private grownIn: Array<string>;


  constructor(name: string, grownIn: Array<string>) {
    this.name = name;
    this.grownIn = grownIn;
  }

  getGrownIn(role: string): Array<string> {
    if (role == "admin") return this.grownIn;
    else return [];
  }

  private
}

let appleFruit = new Fruit("apple", ["India", "China"]);

console.log(appleFruit.name);
// apple

We have defined a simple class ‘Fruit’ and provided it with -

  • a public variable of type string - name
  • a private variable of type array of strings - grownIn
  • constructor to set variable values from initialization
  • method to get value of getGrownIn

We define appleFruit as an object of the class Fruit and initialize it with values for both name and grownIn.

Straight off the bat we see the feature of private variables, which are a thing only in the most recent Javascript standard.

console.log(appleFruit.grownIn);
// Error: Property 'grownIn' is private and only accessible within class 'Fruit'.

We also see how auto-complete works beautifully while typing in all this code.

Use interfaces

We can level-up the above code by using interfaces for additional abstraction.

interface Plant {
  plant?: string;
  type?: string;
}

We have specified two variables and both are optional.

Change the class to implement this interface.

class Fruit implements Plant {
  public name: string;
  private grownIn: Array<string>;

  constructor(name: string, grownIn: Array<string>, public plant: string) {
    this.name = name;
    this.grownIn = grownIn;
  }

  getGrownIn(role: string): Array<string> {
    if (role == "admin") return this.grownIn;
    else return [];
  }
}

let appleFruit = new Fruit("apple", ["India", "China"], "Apple Tree");
console.log(appleFruit.name);

Similar to other languages you can extend a parent class in the interface.

class PlantMatters {
  // ...
}

interface Plant extends PlantMatters {
  // ...
}
comments powered by Disqus