TypeScript hybrid type implementation

后端 未结 2 1986
无人共我
无人共我 2021-01-05 16:47

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 possib

相关标签:
2条回答
  • 2021-01-05 17:26

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

    0 讨论(0)
  • 2021-01-05 17:27

    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;
    }
    
    0 讨论(0)
提交回复
热议问题