Mutability 12 exercises

Infer Strings as Their Literal Types in Objects with as const

There's another interesting feature of as const, which we'll see in this example.

The modifyButton function accepts an attributes object typed as ButtonAttributes, which has type values of "button," "submit," or "reset".

type ButtonAttributes = {
type: "button" | "submit

Loading explainer


00:00 I wanted to show you one more interesting property of AsConst. We have our modifyButton function here, which takes in our button attributes, which has a type of button, submit or reset. And we have our const button attributes down here, which is an object with type button. And of course, we know that this is being inferred as type string, but modifyButton expects an object

00:18 with type button, submit or reset. Now, we can of course fix this error by just using AsConst on the entire object. And saying button attributes is now totally AsConst. And this means that type is now read-only as well as being inferred as it's literal. But we can also remove that

00:35 and just say type button AsConst. And we can say now that button is inferred as its literal type. So we can hover over this and we can see now that it's type button. You notice that it's slightly different from when I put the AsConst down here, where when I put it there, it's read-only type button

00:54 because the entire object is basically inferred as read-only. Whereas like this, it's basically just saying infer this literal string as it's literal. This is really cool. And we can do that further down too. So if we have our type and type down here, we can say AsConst down the bottom here.

01:12 This is like an array of objects. And now in this array of objects, type button is being inferred as type button and type submit is being inferred as type submit. So this is really nice when you just want to make sure a string or a number or a Boolean is being inferred as it's literal. And it's odd because of course,

01:32 we can still modify this, right? So we say button attributes.type equals. We can only modify it to be button, but we still can modify it, which is a curious thing. So this is another tiny little use case for AsConst that you should just keep in the back of your mind anytime that you want to make sure that an object that you declare

01:51 just that literal is inferred AsConst. Quite handy.