TypeScript hybrid type implementation

♀尐吖头ヾ 提交于 2019-11-30 20:57:47

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;
}

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;
  })();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!