DEV Community

Cover image for TypeScript generic types

TypeScript generic types

Chris Bongers on February 26, 2022

When working with types in TypeScript, we assume that we know what kind of type we will be working with. For instance to define this log function:...
Collapse
 
lexlohr profile image
Alex Lohr

One interesting feature missing in that description is that you can limit what types a generic type can be using extends; multiple types can be expressed via union.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Definitely a big pro, I think in tomorrow's article I actually use multiple types 🙌.
Generics in general are such a blessing and great way to control types.

Collapse
 
leob profile image
leob

Java devs will find this feature very familiar :)

Collapse
 
jwp profile image
John Peters

In C# the type passed in may be inferred. It that true here?

Collapse
 
dailydevtips1 profile image
Chris Bongers

Generics can be inferred indeed.
If you define them like this for instance, in which case you can pass the inferred type you want.

But in general it will default to the T anyhow. this could just prove to be a security fallback.

type InferredType = <T>(t: T) => void
Enter fullscreen mode Exit fullscreen mode
Collapse
 
naztech01 profile image
Nazmul Hossain

This is help me to understand

Collapse
 
dailydevtips1 profile image
Chris Bongers

Glad it helped Nazmul 💖

Collapse
 
sachinchaurasiya profile image
Sachin Chaurasiya

Indeed , Typescript generics are life saving.

Collapse
 
alimobasheri profile image
MirAli Mobasheri

This post was really helpful 👍

Collapse
 
dailydevtips1 profile image
Chris Bongers

Thanks MirAli!

Collapse
 
maupanelo profile image
Mauricio Panelo

Oh nice! I'm just learning Typescript and I had no idea of generics. I would have defaulted to using "any".

Thanks for the tip!

Collapse
 
dailydevtips1 profile image
Chris Bongers

Glad it helped!
Generics are so powerful and indeed a valid replacement of any in most cases (when used correctly).

They have way more power than described here, so they can solve a lot of issues 🤯

Collapse
 
dailydevtips1 profile image
Chris Bongers

Awesome!
They definitely take some getting used to, and practive.