Skip to main content

Command Palette

Search for a command to run...

TypeScript - `as const` key word

"Unleashing the Power of 'as const' in TypeScript

Updated
•4 min read•View as Markdown
TypeScript - `as const` key word

TypeScript is a powerful superset of JavaScript that offers developers a number of features that make it easier to write and maintain large-scale applications. One of these features is the ability to use the "as const" keyword. In this blog post, we'll take a closer look at what "as const" does, how it can be used to improve the quality of your code, and see some code snippets to illustrate the use of as const

What is the as const keyword?

The as const keyword is a TypeScript feature that allows you to preserve the literal type of an expression. By doing so, you can ensure that the type of the expression is not changed, even if the expression is reassigned to a different variable.

Consider the following code example:

const colour = "red";
let newColour = colour;
newColor = "blue";

In this example, the type of colour is string, and the type of newColour is also string. However, if you add the as const keyword to the expression, the type of newColour will be "red", which is the literal type of the expression.

const colour = "red" as const;
let newColor = colour;
newColour = "blue"; // Error: Type '"blue"' is not assignable to type '"red"'

Why use as const in TypeScript?

  1. Preventing Type Changes

One of the main reasons to use as const is to prevent the type of a value from changing. This can be especially useful when working with arrays or objects, as it can help to ensure that the type of these values remains consistent throughout your code. Here's an example:

const colours = ["red", "green", "blue"] as const;
let newColours = colours;
newColours[0] = "yellow"; // Error: Index signature in type '["red", "green", "blue"]' only permits reading.

In this example, the type of colours is readonly ["red", "green", "blue"], which means that the elements in the array are read-only. If you try to reassign an element in the array, you will get a compile-time error.

  1. Improving Code Readability

Another benefit of using as const is that it can improve the readability of your code. When you use as const, it makes it clear to other developers that the type of the expression is fixed, and that it cannot be changed. This can help to prevent unintended changes to the type of a value, which can lead to bugs or other issues. Here's an example:

const colours = ["red", "green", "blue"] as const;
const newColours = colours;
console.log(newColours); // Output: ["red", "green", "blue"]

In this example, we use as const on the colours constant to indicate that the type of colours is fixed and cannot be changed. When we assign the value of colours to a new constant newColours, the type of newColours is set to readonly ["red", "green", "blue"], preserving the literal type of the expression. This makes the code more readable, as it's clear to other developers that the type of newColours is fixed and cannot be changed.

  1. Make code less error-prone

Another benefit of using as const is that it allows TypeScript to catch errors that would otherwise go unnoticed. For example, if you have a variable that is declared as a constant, and you accidentally try to reassign it, TypeScript will give you an error. This can help you catch bugs early on and avoid potential problems down the road.

Here is an example of using as const

let myArray = [1,2,3] as const;
myArray.push(4); // This will give an error as myArray is a constant
myArray[0] = 5; // This will also give an error as myArray is a constant

Another benefit of using as const is that it can improve the readability of your code. When you use as const, it's clear that the variable or object is not going to change. This can make it easier for other developers to understand what your code is doing, and can help prevent confusion.

Here is an example of using as const to make code more readable

let myObject = {
  name: "John Doe",
  age: 30
} as const;

function displayUser(user: typeof myObject){
  console.log(`Name: ${user.name}`);
  console.log(`Age: ${user.age}`);
}

displayUser(myObject);

It's important to note that as const only affects the type of the variable or object at compile time, not runtime. This means that the variable or object can still be changed at runtime, it's only the type that is locked.

Conclusion

In conclusion, the as const keyword is a powerful feature in TypeScript that can help you write safer and more maintainable code. By preserving the literal type of an expression, you can ensure that the type of the expression is not changed, even if the expression is reassigned to a different variable. Also, by using as const, you can catch errors early, make your code more readable, and ensure that certain variables or objects are never reassigned. Whether you're working with arrays, objects, or other types, as const can help you write more robust and more maintainable code in TypeScript.