An instance polymorphic function as an argument in TypeScript

In the last line of the next, 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 get error TS1005: '(' expected.

So, I can only instantiate a type argument if I also call a function. Really?

Leaving an instance (next 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 think this is simply not possible in TypeScript. The standard https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#4-expressions says: "TypeScript adds JavaScript expressions with the following constructs: ... Enter arguments in function calls ...", and that, apparently, means "Type arguments only in function calls."

+4
3

, . :

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

, id<number> . ..:

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

. . , , .

let idNum = id as {(x:number):number};
+7

: .

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

: .

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

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

number , . idNum id<number>, .

+1

, . . , typescript ( ) javascript:

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

As you can see, there is no more information about the generic type. Therefore, you cannot refer to anything other than an id function object.

0
source

Source: https://habr.com/ru/post/1624824/


All Articles