Ensure parameter is an array

Viewed 2169

I'm trying to find a way to check whether a function parameter is an array or not. If it is not, turn it into an array and perform a function on it, otherwise just perform a function on it.

Example:

interface employee {
    first: string,
    last: string
}

function updateEmployees (emp: employee | employee[]) {
    let employees = [];
    if (emp instanceof Array) employees = [emp];
    else employees = emp;
    employees.forEach(function(e){
        return 'something'
    })
}

This seems like it would work to me but is throwing a warning of Type 'employee' is not assignable to type 'any[]'. Property 'length' is missing in type 'employee'.

2 Answers

Here is a typesafe function that ensures an array, (using Typescript). It also checks to see if the item is null or undefined, and returns empty array if so, instead of adding it to an array.

function ensureArray<T>(value: T | T[]): T[] {
  if (Array.isArray(value)) {
    return value
  } else if (value === undefined || value === null) {
    return []
  } else {
    return [value]
  }
}

If you DO want an array that contains null or undefined:

function ensureArray<T>(value: T | T[]): T[] {
  if (Array.isArray(value)) {
    return value
  } 
  else {
    return [value]
  }
}

For your example, the usage would be:

function updateEmployees (emp: employee | employee[]) {
    ensureArray(emp).forEach(function(e){
        return 'something'
    })
}

Notice that a null or undefined element will not create a runtime error using the additional check. And the item in your loop is now of type 'employee'.

Related