Essential Types And Notations 20 exercises
Problem

Restricting `Set` Types

Here's an interesting problem in TypeScript where we want to restrict the types of elements that can be added to a Set.

A new Set of userIds is created, but we want it to only be numbers:


const userIds = new Set();
userIds.add(1);
userIds.add(2);
userIds.add(3);
// @ts-expect

Loading exercise

Transcript

00:00 This is an interesting little problem in TypeScript. Let's say you have a set here and this set, you want it to be a set of numbers. Now, you can add a bunch of numbers to this, but this set, it will actually let you add anything you want to. So user IDs here, you can see that we can happily add strings to this.

00:19 We can happily add objects to this because there's nothing actually telling this set up here what type it should be inside the set. So if we look at user IDs here, it seems to be a set of unknown. We'll cover what unknown does later, but it basically says, I don't know what this is. It could be anything.

00:37 So your job is to try to find a way of passing a type to set to basically say you are a set of this thing. Interesting little problem. Good luck with that.