Beginner's TypeScript Section 18 exercises
solution

Pass a Type Argument to Restrict Potential Types

The solution here is pretty interesting.

We can pass in a type argument to the Set to tell it what type it should be:

const guitarists = new Set<string>();

When the argument is in place, we can only add items of that specific type.

This also enables useful things like hovering

Loading solution

Transcript

0:00 The solution here is pretty interesting. You can pass in a type argument to the set to tell it what type it should be. If we remove this, then guitarists gets put to set unknown. Whereas if we add it back, we end up with set string here. That means that you can't add anything that isn't a string in there. You can't add a Boolean.

0:26 Even when you hover over guitarists.add, it's going to tell you that the add there is a value string. This is really cool. This concept is like you can pass in type arguments, as well as function arguments to certain functions. In this case, this is a class actually that we're instantiating.

0:46 What you can do is command-click or right-click there and say, "Go to definition." Then, if you double-click inside there, you can see that we're now in this crazy file called lib.es2015.collection.d.ts. This is where the types for certain parts of JavaScript are actually typed out. You can see that we have interface set here. We're going to dive deeper on this in a future episode.

1:12 What you see here is that there's this T here which represents the type argument. If I don't want to dive deep into there, and I wouldn't blame you, then you can hover over this and you can see that it's typed as unknown here by default. If you don't pass anything, it's going to be typed as unknown.

1:29 This little thing, when you hover over something like this, you'll be able to see if there's a type argument that you can pass there. We can pass in number here if we want to, and that would mean the add 2 is correct, or we can pass in a string. Lots of different constructs in Java Script or in libraries that you might use use this.

1:47 If you want to say const map equals new Map, and we can say that it's a string. This one actually accepts two type arguments, which is the first one is the key and the second one is the value. If we wanted to create a map where the keys were strings and the values were strings, then we would say map.set, and we'd have to pass in a string and then we pass in a value there.

2:12 If we change that to a number, then that is going to error here. This concept that you can pass in type arguments to certain functions and certain constructors and classes is really crucial for understanding TypeScript as a whole.