Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Hybrid Types

I see this example in the Typescript handbook:

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

var c: Counter;
c(10);
c.reset();
c.interval = 5.0;

But when I try to do c(10); or set c.interval = 5.0 I get an error - Cannot set property 'interval' of undefined

I know I can do:

var c: Counter;
c = function(s: number){
 return "'" + s + "'";
}

What's missing - (or is this an incomplete example) ?

Update:

There is a similar question - which answers this question, although, I still find this example convoluted.

like image 446
Foreign Object Avatar asked May 15 '15 23:05

Foreign Object


1 Answers

To complete the example from the Typescript handbook:

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

function createCounter():Counter{
    var counter = <Counter>function(start:number){};
    counter.interval = 123;
    counter.reset = function(){};
    return counter;
}

createCounter()(10);
createCounter().reset();

or

var getCounter = createCounter();
getCounter(10);
getCounter.reset();
like image 92
Foreign Object Avatar answered Oct 11 '22 01:10

Foreign Object