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'.
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'
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With