TypeScript Type of generic function

后端 未结 2 1070
失恋的感觉
失恋的感觉 2021-02-20 01:52

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 t

相关标签:
2条回答
  • 2021-02-20 02:37

    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.

    0 讨论(0)
  • 2021-02-20 02:54

    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.

    0 讨论(0)
提交回复
热议问题