Deeply Apply Read-only Properties to an Object in TypeScript
Here we have the same setup as before: a modifyButton
function that takes in an object of buttonAttributes
which expects a type of ButtonAttributes
containing either "button", "submit" or "reset":
type ButtonAttributes = { type: "button" | "submit" | "reset";};const modifyButton
Transcript
00:00 Okay, we have a very similar setup to what we had before, which is we have a modifyButton function which takes in some attributes. These attributes are typed as button attributes, so type button, submit or reset. Then we have a const down here of button attributes, and it says type button in there, but when we pass that into our function, it's not working because argument of type string
00:19 is not assignable to parameter of type button attributes. Very annoying, and the reason this is happening is because buttonAttributes.type is mutable. Now, we found a solution to this before, which was all about adding an extra type annotation to button attributes. That worked fine, but there's a kind of more interesting way
00:39 that leads into a really, really cool piece of TS syntax. We would be able to basically get the annotation right or get the inference right if we could just say to TypeScript, treat this entire button attributes const here as if none of the properties inside can be changed.
00:58 So make the whole thing kind of like read-only deeply. Your job is to try to find that annotation and see if you can apply it to these button attributes. So now, you basically, these are the only lines of code you're allowed to work on, the const button attributes equals type button, and you're not allowed to use the button attributes type
01:18 in order to do it. There is such a cool way to do it. Good luck.