Essential Types And Notations 20 exercises

Creating Typed Sets

Hovering over Set when it is created shows us a clue:

const userIds = new Set();
// hovering over `Set` shows:
var Set: SetConstructor;
new <unknown>(iterable?: Iterable<unknown> | null | undefined) =>
Set<unknown> (+1 overload)

We've seen the angle brackets <> before whe

Loading solution


00:00 Okay, so the way around this is you basically say okay new set This is like if we hover over this you can see that there's a couple of curly or rather angle braces here These angle braces have a little unknown in them and you can see that set unknown is here now

00:17 we've seen these braces before when we looked at array and we will again when we look at promises and these braces basically say Especially when you see it next to like some parentheses here this is like a function call basically what it's saying is you can pass in a

00:36 Type into this slot. This is a type parameter And what this means is we can actually pass in a type as an argument to set and when that happens We can do this. We can say new set number and

00:51 Now set number if we look at this, it's now corresponds to set number. It creates a set number and What we can see here is if we try to now add ABC into this then it's going to error Argument of type string is not assignable to parameter of type number So suddenly by passing in number to set here it started working

01:12 We could also have done this a different way where we could actually type user IDs here So we can give a type to the variable to user IDs. We can say whatever's in this slot here It has to be a set of numbers and so new set here It's sort of infers backwards TypeScript is so smart in these situations because it knows

01:32 Okay, I'm putting this set into these user IDs I better just morph the type slightly so that it works if I added like an initializer here and I said, you know Hey and B and C Then it reverses it goes the other way and it says Actually, this isn't this doesn't work because you've already put some strings into this set

01:51 And so now it's a set of strings not a set of numbers But when it's unknown and when it can't quite resolve it, then it basically just says Okay, whatever is being whatever it's being passed into it gets the contextual information from there But this syntax is the one I want you to really keenly pick up on we've got a new set and we're passing in something

02:09 Passing in a type argument into a function call very very useful