Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript hybrid type implementation

On http://www.typescriptlang.org/Handbook#interfaces website Hybrid Types are explained. As these are extremely helpful for creating typings to JS - I wonder if it's possible to define a class implementing e.g. such interface:

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

If not then maybe it's possible to create just an object of that type? How?

like image 288
Filip Avatar asked Aug 16 '14 13:08

Filip


2 Answers

I wonder if it's possible to define a class implementing

No

If not then maybe it's possible to create just an object of that type?

Yes. There will be some use of a type assertion (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;
}
like image 146
basarat Avatar answered Sep 28 '22 07:09

basarat


I think the 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;
  })();
}
like image 34
healthycola Avatar answered Sep 28 '22 07:09

healthycola