TypeScript: Check if an Array Constant Includes a Value
The Problem
When an array is marked as a const (readonly), its type becomes a union of its values.
const VALID_VALUES = ['a', 'b'] as const;
const isValid = (value: string): boolean => (
// ❌ Argument of type 'string' is not assignable to parameter of type '"a" | "b"'
VALID_VALUES.includes(value);
)
Solution 1 - Widen the type
Explicitly set the type to account for other possible values.
Caveat: Widens the type across the board.
const VALID_VALUES: Readonly<string[]> = ['a', 'b'] as const;
const isValid = (value: string): boolean => (
// ✅
VALID_VALUES.includes(value);
)
Solution 2 - Assert the type during the check
Cast the constant during the check.
const VALID_VALUES = ['a', 'b'] as const;
const isValid = (value: string): boolean => (
// ✅
(VALID_VALUES as Readonly<string[]>).includes(value);
)