4

In the last line of the following, I want to instantiate a polymorphic function and pass it as an argument.

function id<T> (x:T) { return x; }
console.log ( id<number>(0) )
console.log ( id< (x:number)=>number > (id) (0) )
console.log ( id< (x:number)=>number > (id<number> ) (0) )

I am getting error TS1005: '(' expected.

So it seems I can instantiate the type argument only if I also call the function. Really?

Leaving out the instantiation (next-to-last line) just works.

For reference, this works in C# (note: id<int> ) :

using System;
class P {
    static T id<T> (T x) { return x; }
    public static void Main (string [] argv) {
        Console.WriteLine (id<Func<int,int>> (id<int>) (0));
    }
}

Well I guess it's just not possible in TypeScript. The standard https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#4-expressions says "TypeScript augments JavaScript expressions with the following constructs: ... Type arguments in function calls ..." and this apparently means "Type arguments only in function calls".

3 Answers 3

8

Cleaning up the code sample to be clear about purpose. You want the following:

function id<T>(x: T) { return x; }
(id<(x: number) => number>(id<number>))(0);

Basically want to have id<number> as a variable. i.e.:

function id<T>(x: T) { return x; }
let idNum = id<number>; // This is what you want

That is syntactially incorrect. You cannot create concrete types that way. Sadly you need to use a type assertion that puts the burden of reliability on your shoulders

let idNum = id as {(x:number):number};
0
2

Here's one solution: use interfaces.

function id<T>(x: T) {return x}
interface id<T> { (x:T): T; }

const idNum: id<number> = id;

idNum(1); // ok
idNum('1'); // gives an error

Another way: use a wrapper function.

function id<T>(x: T) {return x}
function idNum(x:number) { return id(x); }

idNum(1); // ok
idNum('1'); // error

You can substitute number with any type you want in both examples. Use idNum instead of id<number> wherever you want.

-2

Type information is used only at compile type to verify type checks. After that it is lost. For example your typescript (without last line) will be compiled to the following javascript:

function id(x) { return x; }
console.log(id(0));
console.log(id(id)(0));

As you can see there is no generic type information present anymore. Therefore you cannot reference to anything else except "id" function object.

1
  • Thanks, but that does not answer the question. Jan 18, 2016 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.