I have an object like below
const foo = (x : Array<string> | string) {
...
}
Now I want to treat x always as an array, I have done this
const y = Array.isArray(x) ? x : [x];
I know I can have another function to do this, looking for some built-in javascript function.
(this is simplified version I am doing this multiple times try to DRY)
>Solution :
You can use [].concat() or wrap the item with an array, and then flatten it:
const fn1 = x => [].concat(x)
console.log(fn1({ a: 1 }))
console.log(fn1([{ a: 1 }]))
const fn2 = x => [x].flat()
console.log(fn2({ b: 2 }))
console.log(fn2([{ b: 2 }]))
If the function only has a single parameter, you can use rest params, and flatten the array of arguments:
const fn = (...x) => x.flat()
console.log(fn({ a: 1 }))
console.log(fn([{ a: 1 }]))