DEV Community

Cover image for Typescript OOD concept for technical interview
Daniel Lee
Daniel Lee

Posted on

Typescript OOD concept for technical interview

Basics

  • class can implement one or more interfaces.

    • ex) class C implements A,B {...}
  • class can extend from one ore more base classes.

    • ex) class C extends A,B {...}

Member visibility

  • public: can be accessed anywhere

  • protected: only visible to subclasses of the class they're declared in. For example,

class Greeter {
  public greet() {...}
  protected getName() {...}
}

class SpecialGreeter extends Greeter {
  public function(){
    this.getName() // good
  }
}

const g = new SpecialGreeter() // subclass
g.greet() // good, public method of the parent class
g.getName() // bad! cannot call a protected method of the parent class
Enter fullscreen mode Exit fullscreen mode
  • private: cannot be accessed even from subclasses, but via getter method

  • static: define properties or methods on the class itself, rather than on instances of the class. It can be accessed without needing to create an instance of the class. For example

class MathUtils {
 static PI = 3.14159;
 static calculateCircleArea(radius: number): number {
  return this.PI * radius * radius
 }

MathUtils.PI // 3.14159
MathUtils.calculateCircleArea(5) //78.53975
Enter fullscreen mode Exit fullscreen mode
  • When to use it?

    • When the functionality is tied to the class rather than an object
    • For constant or utility function that should be shared
    • For singleton-like pattern where one central instance is sufficient
  • abstract: cannot be instantiated (class, field, method). It is a means to serve as a base class for subclasses which do implement all the abstract members. For example,

abstract class Base {...}
const b = new Base() // bad

class Derived extends Base {...}
const d = new Derived() // good
Enter fullscreen mode Exit fullscreen mode

Top comments (0)