Generics for dummies
Let’s say you have a function that needs to return the first element of an array. Array can be of type either string or integer.
Here we have get access to the firstElement which is a type of string. But we don't have access to default string functions we use in Js.But why is this happening?
Answer:- Typescript isn’t able to infer the right type of the return type.
What is Generics:-
(Textbook definition) - Generics enable you to create components that work with any data type while still providing compile-time type safety.
(Easy definition) - Generics in TypeScript let you make parts (like functions or classes) that can handle any kind of data while still making sure your code is error-free when you write it.
How do i use generics (syntax)?
In this example:
<T>
declares a type parameterT
, which can be any type.arg: T
means the argumentarg
can be of typeT
.identity<number>(5)
tells TypeScript thatT
should be replaced withnumber
in this call to theidentity
function.- Similarly,
identity<string>("Hello")
tells TypeScript to usestring
forT
in this call.
Solution to original problem-
<T>
declares a type parameterT
,which can be any type.arr: T[]
means the argumentarr
which can be an array of any typeT
.- We now have access to all the functions associated to that datatype.
- With validation Here we are explicitly telling that the array is of string type or array is of number type.
- Using interfaces
- defined an interface called
Use
r which describes the structure of a user object. The User interface has three properties:fname
,lname
, andmobNumb
. - defined a generic function called
sendUserDetails<T>
. This function takes an array of typeT
as input and returns an element of typeT
. In other words, it takes an array of any type and returns the first element of that array. - created a constant
userOne
which calls thesendUserDetails
function. You've specified that the generic typeT
for this function call isUser
, so theuserInput
parameter is expected to be an array ofUser
objects. You pass an array with one object that fits the structure defined by theUser
interface.