Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Type of generic function

I can't get my head arround the following paragraph in the TypeScript documentation:

"The type of generic functions is just like those of non-generic functions, with the type parameters listed first, similarly to function declarations:"

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: <T>(arg: T) => T = identity;

What does the last line do and why is it used?

As far as I understood, myIdentity is a variable which gets the type of the identity function? And if this is the case why do I need to define such a variable? The function identity already declares what return type I can expect.

like image 313
Mr. Olomu Avatar asked Jan 24 '18 14:01

Mr. Olomu


People also ask

What are the function of generic types in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.

How do you determine what type a generic parameter T is?

You can get the Type that represents T , and use the IsInterface property: Type type = typeof(T); if (type. IsInterface) { ... } If you want to know which interface is passed, just use == to compare the Type objects, e.g.


2 Answers

The last line declares a variable named myIdentity. The variable is of a function type, a generic function (the <T> makes the it the signature of a generic function, more type arguments could be in the list) which takes an argument of type T and returns a value of typeT. And then initializes the variable with the identity function which conforms to the declared signature of myIdentity.

You may want to do this in order to assign different functions to myIdentity based on runtime conditions. Or declare a parameter of this type and pass it to a function that can invoke it later.

like image 109
Titian Cernicova-Dragomir Avatar answered Sep 17 '22 06:09

Titian Cernicova-Dragomir


Lets say that from the compiler perspective explicit type declaration is not necessary because of type inference.

let myIdentity: <T>(arg: T) => T = identity;

is equivalent to

let myIdentity = identity

Nevertheless, from the human side, it can be used for improving code readability.

like image 26
attdona Avatar answered Sep 20 '22 06:09

attdona