A Cool TypeScript Feature You Might Not Know About: as const
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 is 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.
So in summary, as const
is a nifty way to make types more strict and specific in TypeScript. It helps communicate your intent when you want values to be immutable. Give it a try on your next project!
Here are some more examples of how as const
can be used in TypeScript:
Enum Types
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
Tuple Types
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
Function Return Types
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
Object Properties
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!
Happy Coding😊
Top comments (0)