Intro to Generics 9 exercises
solution

Add Constraints to a Generic

Before we get to the solution, let's refresh our memory on how to specify constraints.

In the type world, the way to add constraints is with the extends keyword.

So for a test, we could create a ReturnWhatIPassIn type where T extends string. If we then create an additional Example type a

Loading solution

Transcript

0:00 Just like in the previous solution, the right way to think about this is as a ReturnWhatIPassIn type output, where we have a T, and it's a T over here. Now we can say type Example = ReturnWhatIPassIn.

0:15 Let's say we pass in a number, but we don't want to allow numbers to be passed in. Well, the syntax for this in the type world is to say T extends string is to add a constraint on here.

0:27 This means now that we get an error when this is passed in. "Type number does not satisfy the constraint." This is the constraint string. We can do the exact same thing here. We can say T extends string, pass it on there, and now we get all the errors keyed in properly.

0:42 You notice that this slot here is just like something that you would see in the type world. You can do anything that you want to here, and we're going to still keep on hammering this home over the next few exercises.