Specify Type Constraints with the satisfies Operator
The first step is to determine the structure of our configurations
object.
In this case, it makes sense for it to be a Record
where the keys will be string
and the values will be an object with apiBaseUrl
and timeout
properties.
const configurations: Record< string, {
Transcript
00:00 Okay. First of all, we need to think about what shape we want configurations to be. We probably want it to be a record of string, and then the value of that is going to be API base URL, lovely, which is a string, and then timeout, which is a number.
00:16 Beautiful. And now we're getting an error because not allowed is not allowed in that situation. But there's another error happening below because environment is now typed as string. Because if we think about the configurations variable, this is not being inferred as the thing being passed to it. It's actually just being typed.
00:35 So we have configurations. This is now the key here, type of key of this configurations is record string, or rather, it's just string. So how can we get around this? We need to make sure that configurations is still being inferred as its type, but we need type checking on the thing being passed to it. Well, let's add satisfies.
00:54 Satisfies is perfect for this situation. Because it means that we can say this satisfies this criteria while still having these types inferred. So development, production, and staging are still now in the type. So satisfies is really useful when you're doing key of type of tricks because it means that you can still get the inference,
01:14 still get the single source of truth from the value that you're adding there without needing to override it. Beautiful, beautiful stuff. So satisfies, again, if you're ever declaring a config object, satisfies is probably what you're going to be needing to use.