3 min read
•Question 35 of 48easyWhat are const assertions?
Making values deeply readonly.
What You'll Learn
- as const syntax
- What it does
- Common use cases
as const
Makes values deeply readonly with literal types.
code.tsTypeScript
// Without as const
const colors = ["red", "green", "blue"];
// Type: string[]
// With as const
const colors = ["red", "green", "blue"] as const;
// Type: readonly ["red", "green", "blue"]Effects
code.tsTypeScript
const config = {
host: "localhost",
port: 3000,
debug: true
} as const;
// Type:
// {
// readonly host: "localhost";
// readonly port: 3000;
// readonly debug: true;
// }
config.port = 8080; // Error: readonlyCommon Use Cases
code.tsTypeScript
// Action types
const ACTIONS = {
ADD: "ADD",
REMOVE: "REMOVE"
} as const;
type Action = typeof ACTIONS[keyof typeof ACTIONS];
// "ADD" | "REMOVE"
// Tuple types
function getCoords() {
return [10, 20] as const;
// Type: readonly [10, 20]
}
const [x, y] = getCoords();
// x: 10, y: 20 (not number, number)