Aller au contenu principal

castArray()

castArray<T>(value): T[]

Casts value as an array if it's not one.

💎 Why is this a Hidden Gem?

Normalize any value into an array — the simplest way to write flexible APIs.

DEPRECATED

Use Array.isArray(value) ? value : [value] directly instead.


Type Parameters

T: T

The type of elements.


Parameters

value: T | T[]

The value to inspect.


Returns: T[]

The cast array.


See Also


Since

2.0.0


Also known as

castArray (Lodash, es-toolkit, Radashi) · of (Ramda, Effect) · toArray (Antfu) · ❌ (Remeda, Modern Dash)


Example

// ❌ Deprecated approach
castArray(1); // => [1]
castArray([1, 2, 3]); // => [1, 2, 3]

// ✅ Recommended approach
Array.isArray(1) ? 1 : [1]; // => [1]
Array.isArray([1, 2, 3]) ? [1, 2, 3] : [[1, 2, 3]]; // => [1, 2, 3]

How it works?

Casts value to an array if not already. Deprecated: Use Array.isArray() with conditional.

Native Equivalent

// ❌ castArray(value)
// ✅ Array.isArray(value) ? value : [value]

Use Cases

Ensure array 📌

Ensure value is an array.

const ensureArray = (v) => Array.isArray(v) ? v : [v];

ensureArray([1, 2]); // => [1, 2]
ensureArray(1); // => [1]

Normalize input

Accept single or multiple values.

const ids = Array.isArray(input) ? input : [input];
ids.forEach(process);

Handle optional array

Process parameter that might be array.

const tags = [].concat(tagOrTags);

Normalize component props that accept single or array

Handle component or function parameters that accept both T and T[]. Very common pattern in React components and library APIs for flexible interfaces.

interface NotifyOptions {
recipients: string | string[];
message: string;
}

function notify(options: NotifyOptions) {
const recipients = castArray(options.recipients);
// Always an array, whether user passed "alice" or ["alice", "bob"]
recipients.forEach((r) => sendEmail(r, options.message));
}

notify({ recipients: "alice@example.com", message: "Hello" });
notify({ recipients: ["alice@example.com", "bob@example.com"], message: "Hello" });