TypeScript hybrid type implementation

On the http://www.typescriptlang.org/Handbook#interfaces website Hybrid types are explained. Since they are extremely useful for creating typing for JS, I wonder if it is possible to define a class implementation, for example. such an interface:

interface Counter { (start: number): string; interval: number; reset(): void; } 

If not, is it possible to create only an object of this type? How?

+5
source share
2 answers

I wonder if it is possible to define a class that implements

Not

If not, is it possible to create only an object of this type?

Yes. There will be some use of a type statement (or any ):

 interface Counter { (start: number): string; interval: number; reset(): void; } function getCounter():Counter{ var counter = <Counter>function(start:number){}; counter.interval = 123; counter.reset = function(){}; return counter; } 
+6
source

I think a more updated version is this:

 interface Counter { (start: number): string; interval: number; reset(): void; } function getCounter(): Counter { return (() => { var result: any = (start: number) => "Start!"; result.result = 10; result.reset = () => {} //Converts the temporary variable to the interface type. return <Counter> result; })(); } 
0
source

Source: https://habr.com/ru/post/1200474/


All Articles