If you must have seen <T>, or <extends from T> you must have surely thought WHAT IS THIS!!!. So let us take this easy today & get ourselves through.
What is a Generic in TypeScript?
The TypeScript documentation explains Generics as “being able to create a component that can work over a variety of types rather than a single one.”
Great! That gives us a basic idea. We are going to use Generics to create some kind of reusable component that can work for a variety of types. But how does it do? Here is how:
"The best way to understand what this statement means is to write a generic identity function. The identity function is a function that simply returns whatever argument is passed into it. In plain JavaScript, that would be:
function identity (value) {
return value;
}
console.log(identity(1)) // 1
In typescript:
function identity (value: Number) : Number {
return value;
}
console.log(identity(1)) // 1
It’s nice that we now have a type in there, but the function is not very flexible. The identity function should work for any value passed in, not just numbers.
This is where Generics come in
Generics allow us to write a function that can take in any type and will transform our function based on that type.
function identity <T>(value: T) : T {
return value;
}
console.log(identity<Number>(1)) // 1
Referring to the above image, when we call identity<Number>(1)
, the Number
type is an argument just like the 1
is. It populates the value T
wherever it appears. It can also take in multiple types just like we can have multiple arguments.
There is nothing special about T
or U
, they are just variable names that we choose
This is it about Generics in functions. Moving ahead we will see how Generics work for Classes and Interfaces.
Stay Tuned!!!