Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

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.4 (released in 2019). That's a century in web development, but hey, I'm still starting out!

How to narrow types with const assertions

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.id isn't changed to 234. But TypeScript doesn't know that, and if you inspect the resulting type, you'll find that resource.id 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.

TypeScript code: const resource = {id: '123'};  if (resource.id === '234') {   console.log('yay') }

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! 👏

TypeScript: const resource = {id: '123'} as const;  if (resource.id === '234') {   console.log('yay') }

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.

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles