TypeScript is a strongly typed language, but sometimes you need to build functionality so that it can use any data type. In some cases, we could use the any type:
However, in this case, we cannot use the result of the function as an object of the same type that was passed to the function. For us, this is type any. If instead of the number 5, an object of some class were passed to the function, and then we would have to use this object, for example, call functions on it, then this would be problematic. And to concretize the return type, we can use generics:
With the expression
<T> we indicate that the function getId is typed with a specific type T. When the function is executed, a specific type will be substituted for T. Moreover, at the compilation stage, the specific type is not known. And the function will return an object of this type. For example:
In the first case, instead of the T parameter, the number type will be used, so we can pass a number to the function. In the second case, instead of T, the string type is used, so in the second case, you can pass a string. Thus, we can pass objects of different types to the function, but at the same time strict typing is preserved, each version of a generic function can only accept objects of a certain type.
Similarly, you can also use generic arrays:
In this case, regardless of the type of data passed in the array, all its elements will be combined into one common string.
Thanks goes to these wonderful people (emoji key):