This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
I'm continuing my journey of learning TypeScript, and it's a wild ride. Sometimes I feel like I have things under control, but other times, I'm looking at a type definition at work, and all I can do is scratch my head in confusion. It'll be a long journey!
Today I discovered a somewhat basic but very useful feature that's in TS since 3
(released in 2019). That's a century in web development, but hey, I'm still starting out!
Let's look at a trivial example.
const resource = {id: '123'};
if (resource.id === '234') {
console.log('yay!');
}
If you look at it, you'll probably see that there's no way this code logs out yay!
because the resource
isn't changed to 234
. But TypeScript doesn't know that, and if you inspect the resulting type, you'll find that resource
is just a string
. And that does make sense because it doesn't matter if you declare an object with the const
keyword; you can still change the properties as you like.
But what if you want to treat the object as truly immutable? Turns out, you can narrow types and explicitly tell TypeScript that resource
won't change with two words — as const
.
const resource = {id: '123'} as const;
if (resource.id === '234') {
console.log('yay');
}
And voilà — look at this extra level of type safety! 👏
Now that TypeScript knows that resource
is immutable, it narrows the property type from string
to 123
, and it complains if you're trying to alter the constant object. That's pretty handy for all sorts of operations!
The TypeScript docs are a quick read if you want to learn more.
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2023-02-10T23:00:00+00:00) How to narrow and secure types with const assertions (#tilPost). Retrieved from https://www.scien.cx/2023/02/10/how-to-narrow-and-secure-types-with-const-assertions-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.