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 parameter T, which can be any type.
  • arg: T means the argument arg can be of type T.
  • identity<number>(5) tells TypeScript that T should be replaced with number in this call to the identity function.
  • Similarly, identity<string>("Hello") tells TypeScript to use string for T in this call.

Solution to original problem-

  • <T> declares a type parameter T,which can be any type.
  • arr: T[] means the argument arr which can be an array of any typeT.
  • We now have access to all the functions associated to that datatype.
More examples on Generic
  • 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 User which describes the structure of a user object. The User interface has three properties: fname, lname, and mobNumb.
    • defined a generic function called sendUserDetails<T>. This function takes an array of type T as input and returns an element of type T. In other words, it takes an array of any type and returns the first element of that array.
    • created a constant userOne which calls the sendUserDetails function. You've specified that the generic type T for this function call is User, so the userInput parameter is expected to be an array of User objects. You pass an array with one object that fits the structure defined by the User interface.

Did you find this article valuable?

Support Aditya Revankar by becoming a sponsor. Any amount is appreciated!