Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I annotate recursive types in TypeScript?

If I have a function like this:

function say(message: string) {
    alert(message);
    return say;
}

it has the interesting property that I can chain calls to it:

say("Hello,")("how")("are")("you?");

The compiler will generate a warning if I pass a number into the first call, but it will allow me to put numbers into subsequent calls.

say("Hello")(1)(2)(3)(4)

What type annotation do I need to add to the say function to make the compiler generate warnings when I pass in invalid types to the chained calls?

like image 935
Peter Olson Avatar asked Oct 12 '12 00:10

Peter Olson


1 Answers

A type that references itself must have a name. For example,

interface OmegaString {
    (message: string): OmegaString;
}

then you can annotate say as an OmegaString,

function say(message: string): OmegaString {
    alert(message);
    return say;
}

then the following code will type-check.

say("Hello,")("how")("are")("you?");

but the following will not,

say("Hello")(1)(2)(3)(4)
like image 60
chuckj Avatar answered Oct 02 '22 11:10

chuckj