What is 'as const' or 'const assertions' in TypeScript?
Today, we'll explore the as const
assertion and how it can be used to add even more type safety to our TypeScript code!
What is "as const"?
In TypeScript, the as const
syntax is a way to inform the TypeScript compiler that a certain value (like an object or an array) is immutable – meaning it can't be reassigned or changed.
Here is a simple example of the syntax:
// Array example const starterPokemon = ["Bulbasaur", "Charmander", "Squirtle"] as const; // Object example const charmander = { name: "Charmander", type: "Fire" } as const;
And to understand how this could help, let's look at an example with and without the as const
assertion:
const charmander = { name: "Charmander", type: "Fire" }; // This will result in a TypeScript/JS error: // Cannot assign to 'name' because it is a constant. charmander = { name: "Bulbasaur", type: "Grass/Poison" }; // However, this will NOT result in an error: charmander.name = "Pikachu";
Versus with an as const
assertion:
const charmander = { name: "Charmander", type: "Fire" } as const; // This will result in a TypeScript error: // Cannot assign to 'name' because it is a read-only property. charmander.name = "Charmeleon"; // This too will result in a TypeScript error: // Cannot assign to 'type' because it is a read-only property. charmander.type = "Flying";
Why should we use "as const"?
Immutability: By using
as const
, we're telling TypeScript that our value is not going to change. This can help prevent unintended mutations in our code.Narrowed Types: Instead of having a wide type, using
as const
narrows down the type. For instance, withoutas const
, thetype
property of ourcharmander
object would be inferred asstring
. Withas const
, it's inferred as the string literal"Fire"
, preventing us from assigning any other string to it.
The as const
assertion is a powerful tool that brings both immutability and type narrowing to our TypeScript arsenal.
Happy coding and (Pokémon training! 🚀🔥🌱💧🌩️).
Follow me on Twitter or connect on LinkedIn.
🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉