This page looks best with JavaScript enabled

Classes, Objects, Props and Interfaces in Typescript

 ·   ·  ☕ 2 min read

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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.

1
2
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.

1
2
3
4
interface Plant {
  plant?: string;
  type?: string;
}

We have specified two variables and both are optional.

Change the class to implement this interface.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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.

1
2
3
4
5
6
7
class PlantMatters {
  // ...
}

interface Plant extends PlantMatters {
  // ...
}
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things