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".
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With