Skip to main content

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.

note

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}`);
}