Here is a versatile function that wraps any value into an array:
const ensureArray = <T,>(value?: T | T[]): T[] => {
if (Array.isArray(value)) return value
if (value === undefined) return []
return [value]
}
const undef = undefined
ensureArray(undef) // result type undefined[]
const str = 'string'
ensureArray(str) // result type string[]
const strArray = ['string']
ensureArray(strArray) // result type string[]
interface Interface {
[key: string]: string | string[] | number | number[]
}
const p:Interface ={a:'x'}
ensureArray(p.a)
// types as const ensureArray: <string | number>(value?: string | number | (string | number)[] | undefined) => (string | number)[]
Is there a way to make TypeScript deduce the function type as
(value: string | number | string[] | number[] | undefined) => string[] | number[]
?
Try it out yourself: here