Loading
Current section: 6. Generics 5 exercises
lesson

Intro to Generics

Loading lesson

Transcript

00:00 Alright. It's time to learn about one of TypeScript's most powerful features, and that is generics. Generic functions and generic types. And that's what we're gonna be learning about in this exercise. It's super, super cool.

00:11 So let me just show you the world without generics. It's actually funny. This example, is using a generic. Array is a generic type, but, let's just focus on the function itself. So first number, we're going to, take an array of numbers and return either number of undefined.

00:29 Okay. That's fine. But with generics, you can make it work with any type. So here, you can only use this if you had an array of numbers. But in this case, you can use it if you have an array of anything.

00:41 And so it's a really, really powerful mechanism for you to, be able to make a function that's totally generic. That's the the whole idea. And it uses this syntax, and we're gonna explore that in this exercise. So there, yeah, like pretty much just described this. You have to make an individual function for every type that you care about, whereas, the alternative would be to just type it as any, but now you lose type safety.

01:09 But so by making a generic, you can actually have it, apply to any, type and that's really nice. We also have generic types that we're gonna explore in this exercise. And, just wanted to mention that, yeah, generics are actually everywhere. You have already been using them with, the array generic type. There's also promises we haven't gotten into just yet, but you're gonna be using those a lot.

01:35 Lots and lots of things. And in fact, the the sign of a really, really good library of TypeScript code is one where you actually don't know how complicated the types are behind the scenes, because most of the code that you write to, work with that utility library, should not have to worry about, the fact that generics are in use or anything like that. But all the types should flow throughout the program and make TypeScript really helpful for you. So I'm really excited for you to, get working on this exercise, so let's just get right into it.