Inference Basics 6 exercises

Create Unions from Objects Using Two Operators

Recall that if we only use the typeof operator, we would get the entire object back as the type, which is not what we want.

In order to create a union type out of only the keys of testingFramework object, we need to also use the keyof operator to iterate over each of the top-level keys:

Loading solution


0:00 The solution here is to take our testingFrameworks and use typeof on it, which first of all, extracts the type. If we take off this little keyof thing here, then we end up with vitest, label: string, jest, label

0:12 string.

0:14 What we want to do is take each of these keys, the base keys, and just grab them and iterate of them, create a union type. Luckily, typescript has a helper here to let us do this. It's not this, keyof, like this. It's actually its own key word called, keyof. It's a little bit different from the ones that we've seen before.

0:35 What this means is you get back vitest or jest or mocha. This keyof is super duper useful and we're going to be using it a bunch going forward. As you can see, it looks a little bit strange, especially when it's in line with this typeof. If you try to do this the other way around, then it's not going to let you, because keyof only operates on types, not actual run type things.

0:57 First of all, we need to take this and say, type TestingFrameworks equals this, and then say, keyof TestingFrameworks. You don't need to use it with typeof. You can use it with anything. You can use it with a: string, b: string, c

1:13 string for instance. What you end up with then is going to be a or b or c.

1:19 That's the main use case of keyof and it's especially useful with typeof, because it means that we don't need to declare an extra type there. We're just grabbing it off the runtime construct.