28

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.

1
  • 3
    As for the question "why do I need to define such a variable," the answer is that in this case you don't. It's just there as an example of another syntax for declaring a function with that type. Commented Jan 24, 2018 at 14:48

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

Comments

18

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.

2 Comments

so if I want to define a type type Identity<T> = <T>(arg: T) => T and then define let myIdentity: Identity<T> = (e: T) => e, is that illegal?
Yes, it is wrong. It is legal to declare a generic type alias like type Identity<T> = (arg: T) => T and then use it like let myIdentity: Identity<String> = (arg: String) => arg. Identity<T> is a generic type alias, you have to define a specific type when declaring a variable of type Identity<T>, in this case String.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.