Annotations and Assertions 12 exercises

Combine as const with satisfies for Read-Only Objects

We started with an @ts-expect-error directive inside of routes that was not working as expected.

Because we wanted a configuration object to be in a certain shape while still being able to access certain pieces of it, this was a perfect use case for satisfies.

At the end of the routes obj

Loading solution


00:00 Okay, so we know that we need satisfies because of this TS expect error We're expecting the config to be in a certain shape while still being able to access certain pieces of it So let's say we say satisfies Record string whoops and spell satisfies incorrectly. That's very silly record string and then the object is component string

00:20 Great. That's really nice. So now we have our roots and now things are being inferred properly Now though we're still getting or not getting an error when we try to reassign Members of that thing and component is still being inferred a string instead of home the literal home so we could say now as const here and

00:42 Except though that this isn't the right order if we try to apply as const to a type Because that's what we're doing here This is not going to work as a const assertion can only be applied to references to enum members string

00:57 Number boolean array or object literals. So as const actually needs to apply to the value. So how do we rearrange this? Well, let's try putting as const before the satisfies and this is the correct way to do it So now we say roots as const you can imagine wrapping these in parentheses now this whole thing

01:17 Satisfies record string component string. So that's the operational order We need to do in here and now roots is basically just going to be as consted So we're going to get all of the read-only modifiers. We're going to get all the literals being inferred nicely too and it means that we can't modify them using

01:35 Mutability and when we access them if we dive deep into here So roots this roots and then components and then this is going to be if we hover over it It's going to be about whereas if we go back to the home one, then it's going to be home Fantastic. So this again is a really nice

01:53 Setup when you want to have a configuration object that matches a certain shape and you want it to be as consted. Very cool