Objects 16 exercises

Restricting Object Keys in TypeScript

Here we have a configurations object, typed as Configurations which is currently unknown.

The object holds keys for development, production, and staging, and each respective key is associated with configuration details such as apiBaseUrl and timeout.

There is also a notAllowed key,

Loading exercise


00:00 In this exercise, we have a configurations object here, which is being typed as configurations, which is currently a type which is unknown. We have a string union at the top here called environment, and environment is a union of development, production, or staging literal strings.

00:17 And the configurations object down below, this is an object with development, production, staging as those keys. Except we have a TS expect error here, which is expecting this object on the bottom not allowed to well be not allowed. It shouldn't be assignable as a key.

00:33 So your job is to try to work out the right type for configurations here, where we don't want to have to redeclare development, production, and staging here. We actually just want one type here. It's going to be one line of code. Actually, it might not be one line of code, but it's going to be basically reliant on environment here.

00:54 So that if we add another environment, it will automatically propagate down to configurations. So it's an object with environment as the keys. I think I've given you enough information for that. Good luck.