Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure parameter is an array

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'.

like image 485
Jon Lamb Avatar asked Jan 19 '26 18:01

Jon Lamb


1 Answers

Here's the fixed version of your function:

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

But it can be shorter:

function updateEmployees(emp: employee | employee[]) {
    (emp instanceof Array ? emp : [emp]).forEach(function(e){
        return 'something'
    })
}
like image 131
Nitzan Tomer Avatar answered Jan 21 '26 06:01

Nitzan Tomer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!