Let's learn how to use the Typescript keyof operator to create a union type from the keys of an object to be used as a prop or function argument
Transcript
[00:00] For this TypeScript tip, let's imagine you have this dim object, where you have different colors, name it as primary, primary border, secondary, whatever. And you want to create a function, for example, some component that receives a prop named color, and that color can only be some type where some time is one of these keys. How can you do that? To do that, you can use the combination of two operators, typeof and keyof. Let's create a new type, name it some type, and let's use typeof theme.
[00:44] This will bring the object here from the value world into the type world. So now some type is like that. And now we want only the keys of this type. For that let's use keyOf. That will create this union with only the keys.
[01:05] Let's fix this to make it right. And now let's try to use this function or component, some component, and let's pass a color like dark green. That works. But let's try another thing, color whatever. And you can see there is an error here saying that whatever, the string we use is not part of the union created by the keys of this object.
[01:36] So, to bring an object from the value world into the type world, you use a type of keyword or operator, and then to only select the keys you use the key of operator