Type Variables in TypeScript
To better understand the concept of generics, let's create our first function - the identity function. Such a function returns exactly what is passed to it - with the same type.
Let's first write the variants of our function separately.
Let's write a function that takes a number as a parameter and returns a number:
function func(data: number): number {
return data;
}
Now let's write a function that takes a string as a parameter and returns a string:
function func(data: string): string {
return data;
}
Now let's say we want to make it so that one function does all of this. That is, we want to perform generalization.
For this we use type variable, which stores the data type. Such a variable is declared in angle brackets before the round brackets with the function parameters. Let's declare such a variable, giving it the name T (any name is possible):
function func <T>(here are the parameters) {
return data;
}
After that, we will have a variable T that we can use to put the parameter type into it and then specify it as the return value.
Let's specify the type of our parameter in the form of our variable:
function func <T>(data: T) {
return data;
}
It turns out that the parameter can be passed in any type, and this type will be saved in our variable T.
Now we use the value of the variable T as an indication of the function result:
function func <T>(data: T): T {
return data;
}
Now it turns out that the function result type will be derived from the parameter type. Let's check.
Let's call the function with a number:
console.log( func(3) ); // will output 3
Let's call the function with a string:
console.log( func('x') ); // will bring out 'x'
Make a function that takes either two numbers or two strings as a parameter. The function should return the sum of the parameters as its result.