Const assertions are a powerful feature in TypeScript that allow developers to create immutable literal expressions with more precise types. Introduced in TypeScript 3.4, they provide enhanced type inference and immutability guarantees.
Const assertions use the as const
syntax to tell the TypeScript compiler to infer the most specific type possible for an expression. This results in a readonly type that cannot be widened or modified.
To use a const assertion, simply add as const
after an expression:
const colors = ["red", "green", "blue"] as const;
const point = { x: 10, y: 20 } as const;
Const assertions are excellent for creating readonly arrays with specific literal types:
const directions = ["North", "South", "East", "West"] as const;
// Type: readonly ["North", "South", "East", "West"]
Use const assertions to create objects with readonly properties:
const settings = {
theme: "dark",
fontSize: 14,
showSidebar: true
} as const;
// All properties are readonly and have literal types
While regular const
declarations prevent reassignment, they don't affect type inference. Const assertions provide stronger type guarantees:
const regularArray = [1, 2, 3]; // Type: number[]
const constAssertedArray = [1, 2, 3] as const; // Type: readonly [1, 2, 3]
regularArray.push(4); // Allowed
constAssertedArray.push(4); // Error: Property 'push' does not exist on type 'readonly [1, 2, 3]'
Const assertions are a valuable tool in TypeScript for creating immutable, precisely-typed literal expressions. By leveraging this feature, developers can write more robust and type-safe code, especially when working with configuration objects, constants, or any scenario where immutability is desired.
To further enhance your TypeScript skills, explore related concepts such as union types and TypeScript utility types.