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'.
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'.
-
You switched around the
if
/else
– pushkin Commented May 31, 2017 at 0:59 -
This kind of polymorphism is a bad idea in general. Just make
updateEmployees
take an array. If you want to call it with a single employee, then do so withupdateEmployees([emp])
. – user663031 Commented Jun 4, 2017 at 7:34
2 Answers
Reset to default 6Here'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'
})
}
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'.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744848550a4596989.html
评论列表(0条)