How does 'as const' behave differently when applied to an array literal versus a plain object literal?
Short answer
Applied to an array literal, 'as const' converts it from a general array type (like number[]) into a fixed-length, readonly TUPLE type with each element's specific literal type preserved — the same underlying mechanism as with objects, but the array-specific result is a tuple…
Advertisement
AModel answer
Applied to an array literal, 'as const' converts it from a general array type (like number[]) into a fixed-length, readonly TUPLE type with each element's specific literal type preserved — the same underlying mechanism as with objects, but the array-specific result is a tuple rather than just a 'more precise object'.
const colors = ['red', 'green', 'blue'] as const;
// inferred as: readonly ['red', 'green', 'blue']
// NOT string[], and NOT a mutable arrayReal-world example
Deriving a precise union type of allowed values directly from an array of literal constants, often combined with 'typeof' and indexed access.
Likely follow-ups
- How would you derive a union type like 'red' | 'green' | 'blue' FROM this const-asserted array automatically?
Related topics