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:
This will give us back
"vitest" | "jest" | "mocha" as our test expects.
Note that the
keyof operator has its own dedicated keyword instead of being called something like
If we tried to use
typeof in reverse, it wouldn’t work:
The reason this won’t work is because
keyof only works on actual types, instead of working on runtime code like
Similar to what we’ve seen before, we can make the
TestingFramework type more readable by extracting
typeof testingFrameworks out into its own type called
keyof on its Own
As seen below, it’s possible to use
In this case,
TestingFramework would be
"a" | "b" | "c".
As long as you are passing a type to
keyof you’re good.
However, the combination of
typeof is really useful since since you can grab the type off of the runtime construct instead of the extra step of creating a type.
We’ll be using
keyof a lot going forward!
[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.