Combine keyof and typeof to Derive Types
We have configurations
where each is a value we want to turn into a type:
const configurations = { development: { apiBaseUrl: "http://localhost:8080", timeout: 5000, }, production: { apiBaseUrl: "https://api.example.com", timeout: 10000, }, staging: {
Transcript
00:00 So this is a bit of a mind bender, right? We have our configurations and our configurations are a value and we want to turn that value into a type. We've not sort of seen this before. This doesn't seem possible given our skill set, but let's just declare type configurations like this,
00:16 configurations, and we're going to say is type of configurations. Whoa, look at that. No errors. This all seems fine. And what's happening here is that the type of configurations here, if we hover over it, you can see it's being inferred as this type. This is now being captured in a type alias.
00:35 So now we have this development production staging captured in a type. And if I were to say, let's say const configurations two is of type configurations, then I would need to fill in all of the slots that were kind of declared in configurations. Really, really cool.
00:53 And now of course we know that using the key of thing that we saw earlier, we can just say, instead of development, production or staging, we can look at this type and say, Oh, well that's development, that's production, that's staging. Let's stick that in a key of. So we can say key of configurations and now hover over environment.
01:11 We've got development or production or staging. Incredible. There's an even simpler solution than this. We don't need to declare this type of in a separate type alias. I just did that sort of for teaching purposes and a really common setup that you're going to see out in the wild all the time is key of type of
01:29 configuration. So type of, of course, declares it in a new type alias and key of then runs key of on top of that. So you might think, okay, why not just do like, uh, why not? Like why does it have to be this order? Why type, why not type of key of like this? Well, if you think about it,
01:45 key of only works on types. And of course this is a value. So you have to turn it into a type first, which is what type of does and then run key of on that type. And you end up with development, production and staging. This is mind blowing, right? We are basically just using a sort of type transformation on a runtime value,
02:06 taking that and turning it into something that we can then feed into typing our other applications. And of course, if we add something to this, like QA for instance, then that is going to end up inside this type. So, so cool.