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;
}
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;
}
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;
}
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
this compiler giving me options as L and XL as an autoComplete.But if I type other string it will give error.
We can do like this
type Size = 'L' | 'XL' | string;
But compiler loosing the autoComplete for 'L' and 'XL' and at the same time Size is becoming string data type.
here is the solution
type Size = 'L' | 'XL' | Omit<string, 'L' | 'XL'>
Now you can see compiler giving me the auto-complete for L and XL
Also it didn't complain when I give other string
Lets put this in generic way
type Selective<T extends string> = T | Omit<string,T>
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')
Adios. Love Coding. Give it a thumbsup if you like it. Thanks.
Top comments (0)