6

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.

Community
  • 1
  • 1
Foreign Object
  • 1,630
  • 11
  • 22
  • I think what the book is saying is that you can describe types for such patterns. For example a function that has properties on the function itself, like a constructor with static methods. – elclanrs May 15 '15 at 23:38
  • Sure, I get that - but why `c(10)` if I can't actually call `c` that way. Is there an intermediary step that's missing. – Foreign Object May 15 '15 at 23:41
  • From what I understand the example is not meant to be run. `c` can be any object that adheres to that interface. It is just showing that you can do it. That's what I see anyway. – elclanrs May 15 '15 at 23:49
  • Ok, so there is a step missing - just wanted to clarify, I'm just starting to dive into Typescript - thank you for your help. – Foreign Object May 15 '15 at 23:56
  • @elclanrs - if you're interested check out my answer below. – Foreign Object May 16 '15 at 00:42

1 Answers1

7

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();
Foreign Object
  • 1,630
  • 11
  • 22