Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript an interface can extend a class, what for?

in TypeScript Handbook in 'Using a class as an interface' section, there is an example of an interface which extends a class.

class Point { ... } interface Point3d extends Point {...}

When can this be useful? Do you have any practical examples of this?

like image 626
zuraff Avatar asked Aug 24 '16 13:08

zuraff


1 Answers

Take this class for example:

class MyClass {     public num: number;     public str: string;      public constructor(num: number, str: string) {         this.num = num;         this.str = str;     }      public fn(arr: any[]): boolean {         // do something     } } 

You can create an instance like so:

let a1 = new MyClass(4, "hey"); 

But you can also create an object that satisfies the same exact interface like so:

let a2 = {     num: 3,     str: "hey",     fn: function(arr: any[]): boolean {         // do something     } } 

The a1 is an instanceof MyClass, while a2 is just an object, but they are both implementing the same interface.
The point of interfaces extending classes is exactly that, you can take the interface that the class defines and extend it.

Maybe it's just a possibility due to the nature of the language, but here's an example of where it might be useful:

class Map<T> {     private _items: { [key: string]: T };      set(key: string, value: T) { ... }      has(key: string): boolean { ... }      get(key: string): T { ... }      remove(key: string): T { ... } }  interface NumberMap extends Map<number> {} interface StringMap extends Map<string> {} interface BooleanMap extends Map<boolean> {}  function stringsHandler(map: StringMap) { ... } 
like image 94
Nitzan Tomer Avatar answered Sep 28 '22 02:09

Nitzan Tomer