Intro to Generics 9 exercises
explainer

The Importance of Generics in TypeScript

Orta Therox, an ex-TypeScript team contributor, answers a question about what TypeScript would be like without generics.

He explains that TypeScript's complex structural type system needs the ability to reuse fields provided by generics. Without them, types would be longer and more repetitive.

He

Loading explainer

Transcript

0:00 As part of the interviews for Total TypeScript, I interviewed Orta Therox, who's an ex-TypeScript team contributor and helped to write a lot of the handbook, and I asked him a really interesting question. I asked him what would Typescript look like without generics?

0:15 Oof! You can't make a type system that is as complicated and feature-rich as TypeScript without generics. It's just like, as a structural type system, which means the type system that checks every single field to see if they match the other thing that it's been compared against, you just come to a point where you need the ability to reuse fields in some way.

0:44 If you didn't have that, your types would be incredibly long and incredibly large amounts of overlapping code between each of them. So generics gives you that reusability that is kind of essential to build any sort of complicated type system.

1:01 I mean, I say that, but I used Objective-C for about ten years and it does not have generics. It has a thing called lightweight generics. We got by, but you needed a type system in that case that's nominal, wherein every single class has a unique type that, if you compare a type of an animal to the type of a dog, those two are always different.

1:23 Whereas in TypeScript they could be the exact same and they could be treated the exact same in different cases...