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