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