What does “as const” mean in TypeScript, and when should it be used?
I came across the as const
cast in TypeScript but couldn’t fully grasp its purpose. I checked some documents and videos, but I’m still unsure.
For example, in the following code:
const args = [8, 5] as const;
const angle = Math.atan2(...args);
console.log(angle);
What does as const
do here, and what benefits does it provide?
In TypeScript, using as const is a great way to infer literal types. For example:
const args = [8, 5] as const;
This ensures that args is inferred as the specific tuple [8, 5] rather than a general array of numbers (number). This is useful when you need to pass exact values to functions that require literal types.
@Shielagaa @yanisleidi-rodriguez
Another common use of as const TypeScript is to make an array immutable. By adding as const to your array:
const directions = ['north', 'south', 'east', 'west'] as const;
TypeScript treats directions as a read-only tuple, preventing any accidental modifications. This is particularly helpful when you need to ensure the values in an array stay constant.
In TypeScript, as const can also be used to narrow down types when passing arguments to functions. For example:
const point = [10, 20] as const;
function plot(x: 10, y: 20) { console.log(`Plotting at (${x}, ${y})`); }
plot(...point); // Works because point is treated as [10, 20]
Here, as const TypeScript ensures that point is treated as a literal tuple, so TypeScript can infer the types of x and y more accurately and prevent type mismatches.