TypeScript Developer interview question · Most asked
What does `as const` do?
Summary
as const makes TypeScript infer the narrowest possible type: literal types instead of string/number, readonly properties, and readonly tuples instead of arrays.
Longer Answer
It's commonly used to derive union types from runtime arrays or objects, giving a single source of truth: const ROLES = ['admin', 'user'] as const; type Role = typeof ROLES[number];. Combine with satisfies for validated, literal configs.
Code Example
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
const config = { retries: 3, mode: "strict" } as const;
// config.mode = "loose"; // Error: readonly
Key Points
- Literal types instead of widened ones
- Deep
readonly - Readonly tuples
- Derive unions from runtime values
More most-asked TypeScript Developer questions
- Explain `any`, `unknown` and `never`.
- What are the differences between `interface` and `type` aliases?
- What is structural typing in TypeScript?
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is TypeScript and what problems does it solve?