Convert a value to an array
npx @tessl/cli install tessl/npm-arrify@3.0.0Arrify provides a simple utility function that converts any value to an array format. It handles various input types including null/undefined (returns empty array), existing arrays (returns as-is), strings (wraps in array), and iterable objects like Sets (converts to array using spread operator).
npm install arrifyimport arrify from "arrify";Note: This package is ES module only. CommonJS is not supported starting from v3.0.0.
import arrify from "arrify";
// Convert string to array
arrify('π¦');
//=> ['π¦']
// Arrays are returned as-is
arrify(['π¦']);
//=> ['π¦']
// Convert Set to array
arrify(new Set(['π¦']));
//=> ['π¦']
// Null and undefined become empty arrays
arrify(null);
//=> []
arrify(undefined);
//=> []Converts any value to an array using intelligent type-based conversion rules.
/**
* Convert a value to an array.
* @param {any} value - The value to convert to an array
* @returns {Array} The converted array
*/
function arrify(value);Conversion Rules:
null or undefined β empty array [][string][...value][value]Usage Examples:
import arrify from "arrify";
// String conversion
const stringResult = arrify('hello');
// Result: ['hello']
// Boolean conversion
const boolResult = arrify(true);
// Result: [true]
// Number conversion
const numResult = arrify(42);
// Result: [42]
// Object conversion
const objResult = arrify({ key: 'value' });
// Result: [{ key: 'value' }]
// Map conversion (iterable)
const mapResult = arrify(new Map([[1, 2], ['a', 'b']]));
// Result: [[1, 2], ['a', 'b']]
// Set conversion (iterable)
const setResult = arrify(new Set([1, 2, 3]));
// Result: [1, 2, 3]
// Array identity (returns same reference)
const arr = ['existing'];
const arrayResult = arrify(arr);
// Result: ['existing'] (same reference as arr)
console.log(arrayResult === arr); // trueThis package includes comprehensive TypeScript definitions with advanced generic types:
/**
* Convert a value to an array.
* Specifying null or undefined results in an empty array.
*/
function arrify<ValueType>(
value: ValueType
): ValueType extends (null | undefined)
? []
: ValueType extends string
? [string]
: ValueType extends readonly unknown[]
? ValueType
: ValueType extends Iterable<infer T>
? T[]
: [ValueType];The TypeScript types provide precise return type inference based on the input type:
arrify(null) β []arrify(undefined) β []arrify('text') β [string]arrify(['a', 'b']) β string[] (preserves array type)arrify(new Set<number>([1, 2])) β number[]arrify(42) β [number]