Annotations and Assertions 12 exercises
Problem

Improve Type Annotations with the satisfies Operator

Here we have a config object, defined as a Record. The keys in this Record are strings, and the values are a Color that can either be a string or an object with red, green, and blue properties:


type Color =
| string
| {
r: number;
g: number;
b: number;
};
cons

Loading exercise

Transcript

00:00 In this exercise, we have a config object and that config object is a record and it's a record where it has a keys which are strings and it has colors as the values and a color in this universe is either a string or it's an object with RGB on it.

00:16 Now, when we go to access our config in which we've declared foreground as RGB background as RGB and border as a string, then TypeScript doesn't understand that border itself is actually, you know, something that we is a string.

00:31 So we can't do config.border.toUpperCase, it seems, nor can we do config.foreground.r because we can't access properties on like property r does not exist on type string and we can't like get errors here when we try to access things that don't exist.

00:49 So config.primary, config.secondary don't exist and but because we're using a record here, it's like it's yelling at us. So your job here is to try to work out how we can better annotate config so that it still gives us type checking when we add things to it.

01:07 So we can't add numbers to this or let's say like objects without RGB on it, but that we still can just access members of it without needing to do any narrowing and we still get this right behavior down the bottom here.

01:23 So we're looking for these errors to go away just by changing an annotation on config. And I think you're going to need the satisfies operator. Good luck.