Let's break it down, shall we?
function myFn<T>(param: T): T {
return param;
}
function
: its Typescript keyword, denoting that you are declaring a function.
myFn
: the name of the function
in point 1.
<T>
: This means that the function declare is gonna use a generic type: either in the arguments that it's gonna take in, or the return type. You, as a developer, will need to set it explicitly.
(param:T)
: You have exactly one argument, by the name of param
. At the same time, param
is of type T
, which you have set so in point 3.
:T
: This denotes that the function which you declared in point 1 will have to return a value of type T
.
{ return param }
: returns the value of param
. Note that this is allowed, because param
is of type T
and your function needs to return a type T
. Let's consider another snippet:
This is not allowed:
function myFn<T>(param: T): T {
return 0;
}
Reason being 0
is of type number
and not type T
.
Let's put it in pure English:
You are declaring a function
called myFn
which gonna take in an argument of type T
and is going to return a value of type T
.
That's it. Now, on the real usage:
let identity = myFn<string>("hello world");
The variable identity
will be reference of a function that takes in an argument(remember params?) which is of type string
. It will return the value of type string
as well -- and according to the function declaration, it is going to return "hello world"
.
You can read more on Type Assertion of Typsecript