Here are some examples of "as const" :
Enum Types
Tuple Types
Function Return Types
Object Properties
Have you ever worked with types in TypeScript and found yourself wanting more control over how those types behave? Well, there's a handy little feature called as const
that can help with that.
as const
is a way to make type checks stricter by preventing certain operations on a value. For example, let's say we have an array:
const fruits = ['apple', 'banana', 'orange'];
By default, TypeScript sees this as an array that can contain any string. But what if we wanted TypeScript to know that this array will only ever contain these three specific string values?
That's where as const
comes in. By adding it, we make TypeScript treat the array in a more "specific" way:
const fruits = ['apple', 'banana', 'orange'] as const;
Now, instead of just being a string[]
, fruits are seen as the specific tuple type ['apple', 'banana', 'orange']
.
This means TypeScript will give us errors if we try to add or remove items from the array. It knows the values are "locked in". as const
works on other types too.
For example, you could mark an object as constant to prevent adding or removing properties:
interface Cat {
name: string;
age: number;
}
const garfield = {
name: 'Garfield',
age: 10
} as const;
Now Garfield is seen as an object with very specific fields, rather than a loose Cat interface.
Here are some more examples of how as const
can be used in TypeScript:
You can make an enum as const
to remove the implicit number types:
enum Colors {
Red,
Green,
Blue
}
let c = Colors.Green; // number
enum ColorsAsConst {
Red,
Green,
Blue
} as const;
let c = ColorsAsConst.Green; // ColorsAsConst.Green
Mark a tuple as const
to make its types very specific:
let tuple = [1, 'two'] as const;
tuple[0].toFixed(); // OK
tuple[1].toLowerCase(); // OK
Mark a function return value as const
to narrow its type:
function createError() {
return {message: 'an error'} as const;
}
const err = createError();
err.message = 'something else'; // Error
Objects marked as const
prevent adding/removing properties:
interface Point {
x: number;
y: number;
}
const p = {x: 0, y: 0} as const;
p.z = 0; // Error
So in summary, as const
brings immutability and more precise types to enums, tuples, return values, objects, and more!
In summary, const proves to be a clever tool for enforcing stricter and more specific types in TypeScript. It serves as a clear communication of your intent when you require values to remain immutable. Don't hesitate to implement it in your upcoming projects!
Thank you for Reading this article💖
Also published here.