isOneOf()
isOneOf<
T>(value,source):value is T
Checks if a value is one of the values in a readonly array.
💎 Why is this a Hidden Gem?
A robust type guard for verifying values against a readonly list of allowed constants.
Returns false for null/undefined. Useful for validating string unions.
Type Parameters
T: T extends string
The string literal type.
Parameters
value: string | null | undefined
The value to check (can be null or undefined).
source: readonly T[]
The readonly array of allowed values.
Returns: value is T
true if the value exists in the source array, false otherwise.
Since
1.0.0
Example
const statuses = ['pending', 'active', 'done'] as const;
isOneOf('pending', statuses); // => true
isOneOf('invalid', statuses); // => false
isOneOf(null, statuses); // => false
// Type narrowing
const input: string | null = getInput();
if (isOneOf(input, statuses)) {
input; // => 'pending' | 'active' | 'done'
}
How it works?
Type guard that checks if a value is one of the values in a readonly array. Useful for validating string unions at runtime.
Type Narrowing
Null Safety
Use Case: API Validation
Use Cases
Validate string enums/unions 📌
Check if a string belongs to a specific set of allowed values and narrow the type. Critical for validating API inputs or state machine transitions.
const STATUSES = ['pending', 'active', 'done'] as const;
if (isOneOf(status, STATUSES)) {
// status is narrowed to 'pending' | 'active' | 'done'
updateStatus(status);
}
Guard state machine transitions
Validate that a transition is allowed from the current state.
const ALLOWED_FROM_PENDING = ['approved', 'rejected'] as const;
function transition(current: string, next: string) {
if (current === 'pending' && isOneOf(next, ALLOWED_FROM_PENDING)) {
// next is narrowed to 'approved' | 'rejected'
return next;
}
throw new Error(`Invalid transition: ${current} → ${next}`);
}