Loading
Current section: 6. Conditional Types 4 exercises
solution

Infer

Transcript

00:00 Alright. Let's jump right in. So we're going to create an array element type. So type array element, it's gonna accept a type. If that type accept extends array and for u, then we're gonna do u.

00:11 Otherwise, we wanna return never. So if it if it is not an array, then we're gonna say, no. This this case does not apply in this situation. So here we can say array element, of our numbers. We've got numbers and strings, and also we've got users and, just a regular string.

00:28 So in this case, we're gonna, pull out number, then we'll pull out string. We'll be able to pull out the user and, in this case, we pull out never because this is not an array. K. Perfect. That's very similar to what we just did, so that should work out or hopefully was pretty straightforward.

00:44 Now we have our promise result. This is kind of similar to awaited, but awaited does a whole lot more stuff. So if we extend a promise and we'll infer you, then we'll go with you. Otherwise, we'll go with whatever was given to us. So then coming down here, we have our promise of a string.

01:02 We should get a string back. Get a promise of a number, we should get a number back. And a promise of a boolean that just gives us the boolean. So if that was awaited, then that would work just fine. This does work similar to awaited but not quite the same.

01:14 So if it's a promise of a promise, then in this case, we're gonna end up with a promise of string whereas awaited, it's gonna resolve all the way down. So we're not quite there but, yeah. Using infer to, make that magic happen. So pretty cool. And now we're gonna make a function return.

01:32 So this is the return type. Here, we're going to say if the type given extends a function so here earlier, we said just plain function, for the function type, but we want the return of that. And, where are we gonna get u? Well, we get it by inferring it. So we're going to, type it out as an array an arrow function, but our function return will work for any type of function.

01:57 This is just the syntax to represent the type of an arrow function. So here we're gonna say it accepts any arguments, and whatever it returns is what I wanna infer. And so infer that and we'll return that. If it's not a if it doesn't extend something, that matches this type, then give us back never. And so then we can say function return on this string, we should get a string.

02:20 On this one, we should get a boolean. And if we were to do an r three, then let's do a function return of just boolean and that should give us never. Alright. And that is some of the really fun, different types that, that you can create using infer. Of Of course, you can practice this extra at a function and play around with this a bit, but that is the basics of using some of these advanced conditional types.

02:48 So good job.