DEV Community

Cover image for Power of Generics
aravind_akay
aravind_akay

Posted on

Power of Generics

Today I want to discuss very shortly about one such use case of generics. Nowadays everyone want to leverage the usecase of typescript. A quick introduction about generics also would be better to begin with.

What are Generics in Typescript ?

From my point of view , generic is something an alias for a data type which would be unknown. According to google, by definition

Generics are code templates that you can define and reuse throughout your codebase. They provide a way to tell functions, classes, or interfaces what type you want to use when you call it.

Lets say you have a function

function helper(param:string):string {
  return param;
}
Enter fullscreen mode Exit fullscreen mode

Here you can see you are passing a string as a parameter which is denoted by param:string and return type is string which is denoted by ():string.

let's say you have a situation that you don't know what data would come here as a parameter and the same data type you are gonna return .

This is where generics are useful. You can type your function as

function helper<T>(param:T):T {
  return param;
}
Enter fullscreen mode Exit fullscreen mode

Now this function knows your data type and assigns your same data type as return.
In my View

function helper<UnknownDataType>(param:UnknownDataType):UnknownDataType {
  return param;
}
Enter fullscreen mode Exit fullscreen mode

I think you have an understanding about generics. Lets dive into the use case.

We have a situation that you should allow all the strings and selective strings. For example,

You should allow the user to enter size as 'L' and 'XL' means

Image description

this compiler giving me options as L and XL as an autoComplete.But if I type other string it will give error.

Image description

We can do like this

type Size = 'L' | 'XL' | string;
Enter fullscreen mode Exit fullscreen mode

But compiler loosing the autoComplete for 'L' and 'XL' and at the same time Size is becoming string data type.

Image description

here is the solution

type Size = 'L' | 'XL' | Omit<string, 'L' | 'XL'>
Enter fullscreen mode Exit fullscreen mode

Now you can see compiler giving me the auto-complete for L and XL

Image description

Also it didn't complain when I give other string

Image description

Lets put this in generic way

type Selective<T extends string> = T | Omit<string,T>
Enter fullscreen mode Exit fullscreen mode

Now the code is like

type Selective<T extends string> = T | Omit<string,T>

type Size = Selective<'L' | 'XL'>

function makeShirts(i:Size) {
  return 'hello'
}

makeShirts('XS')
Enter fullscreen mode Exit fullscreen mode

Adios. Love Coding. Give it a thumbsup if you like it. Thanks.

Top comments (0)