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?
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) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With