Extracting Types from as const Values
What you'll learn: How to use typeof with as const to automatically derive precise literal types from constant values.
When you mark a value with as const, TypeScript locks down its exact literal shape. But what if you want to capture that specific type for reuse? This is where typeof becomes your extraction tool.
The Core Idea
The typeof operator in TypeScript doesn't just check runtime types—it can extract the compile-time type of a value. When combined with as const, it gives you a type that perfectly mirrors your constant's literal structure.
const colors = ['red', 'green', 'blue'] as const;
// Extract the type from the value:
type Color = typeof colors[number];
// Color is now: 'red' | 'green' | 'blue'
Here, typeof colors gives you readonly ['red', 'green', 'blue']. Adding [number] accesses the array element type, producing a union of all three string literals.
Object Type Extraction
This pattern is especially powerful with configuration objects:
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000,
retries: 3
} as const;
type Config = typeof config;
// Config is: { readonly apiUrl: 'https://api.example.com'; readonly timeout: 5000; readonly retries: 3 }
type ApiUrl = typeof config.apiUrl;
// ApiUrl is: 'https://api.example.com'
Why This Matters
Instead of maintaining values and types separately, you define the value once with as const and extract types as needed. This keeps your code DRY and ensures your types always match your actual data.
Key Takeaway: Use typeof with as const values to derive exact literal types, eliminating duplicate type definitions and keeping your source of truth in one place.