Mutability 12 exercises
solution

Using as const to Deeply Apply Read-only Properties to an Object in TypeScript

By adding as const to buttonAttributes, a readonly modifier is applied to the type.

This fixes the inference issue on type so it will be inferred as a button and not a string:


type ButtonAttributes = {
type: "button" | "submit" | "reset";
};
const buttonAttributes = {
typ

Loading solution

Transcript

00:00 Okay, Button Attributes then. How do we make this read-only, like deeply? Well, we can add AsConst to Button Attributes. Before, Button Attributes was being inferred as type String, so type was mutable.

00:15 But then if we add AsConst, it now adds a read-only modifier to that type. Not only that, but it's now being inferred as Button instead of just type, or just String, rather.

00:29 Beautiful stuff, and this is such a nice pattern because we're going to see the applications of this pattern in a bunch of different ways. Like, declaring configuration objects in TypeScript is really, really common. You know, like different environments for different keys and things.

00:45 And so being able to say, okay, this entire object is consted is just beautiful. And of course, this has no runtime cost. This just disappears at runtime. And so, of course, TypeScript very rarely, and I think pretty much never, touches your runtime code,

01:01 apart from if you're using a couple of features, which we'll talk about way further down the line. But just by adding this type annotation, you get read-only on it. So if I say ButtonAttributes.type equals whatever, it's not going to let me do that. And it infers the literal. AsConst. Very, very useful, as we'll see.