Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instantiated polymorphic function as argument in TypeScript

Tags:

typescript

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".

like image 544
d8d0d65b3f7cf42 Avatar asked Mar 13 '23 14:03

d8d0d65b3f7cf42


1 Answers

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};
like image 104
basarat Avatar answered Apr 24 '23 16:04

basarat