This is the 21st day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
In languages like C# and Java, generics can be used to create reusable components that can support multiple types of data. This allows users to use components with their own data types.
define
Generics is the property of defining functions, interfaces, or classes without specifying a specific type in advance, but specifying the type at the time of use.
Simple example
Let’s look at an example to understand generics:
So let’s first look at a function
function echo(arg){
return arg
}
const result = echo(123)
Copy the code
Here our variable result will be of type any as shown:
So we know that the range of any types is very large and we should try to minimize the use of any type, which would be better if we used generics.
Let’s rewrite the function as a generic:
function echo<T> (arg:T) :T{
return arg
}
const result = echo(123)
Copy the code
In the example above we add
after the function name, where T is used to refer to any input type, and we do not specify a type for the result variable, but our result variable is automatically typed based on type inference. In the above code, the result variable is automatically typed as a number.
We can also manually give it a specific type, such as string:
function echo<T> (arg:T) :T{
return arg
}
const result:string = echo('123')
Copy the code
Multiple type parameters
When we define generics, we can also define multiple type parameters at once. Let’s look at a scenario:
We have a tuple with two values of arbitrary type and at this point we’re going to return the new tuple and swap them
Code:
function swap<T.U> (tuple:[T,U]) :U.T]{
return [tuple[1], tuple[0]]}const result = swap(['str'.123])
console.log(result[0]);
console.log(result[1]);
Copy the code
Print result:
The data types are:
Of course we can also use the first one as a number for example:
function swap<T.U> (tuple:[T,U]) :U.T]{
return [tuple[1], tuple[0]]}const result = swap(['str'.123])
result[0].toExponential()
Copy the code
Use the second value as a string:
function swap<T.U> (tuple:[T,U]) :U.T]{
return [tuple[1], tuple[0]]}const result = swap(['str'.123])
result[1].length
Copy the code
So it doesn’t even report an error.