I would like to create helper function that will ensure that value is wrapped in array.
- if value is
null
orundefined
return empty array - if value is array, leave it as is
- else wrap value in array
What I don't understand is what is typescript complains about, how to fix it and is there a way to get more descriptive error message:
function ensureArray<T>(
value: T,
): T extends undefined | null ? [] : T extends Array<any> ? T : T[] {
if (value === undefined || value === null) {
// Type '[]' is not assignable to type 'T extends null | undefined ? [] : T extends any[] ? T : T[]'.(2322)
return []; // should I just use as any?
}
// Type '(T & any[]) | [T]' is not assignable to type 'T extends null | undefined ? [] : T extends any[] ? T : T[]'.
// Type 'T & any[]' is not assignable to type 'T extends null | undefined ? [] : T extends any[] ? T : T[]'.(2322)
return Array.isArray(value) ? value : [value];
}
const x1: number[] = ensureArray(1)
const x2: number[] = ensureArray([1, 2])
const x3: string[] | [] = ensureArray('str' as string | null)
CodePudding user response:
You don't need the conditional type !
function ensureArray<T>(
value: T | Array<T> | undefined | null,
): T[] {
if (value === undefined || value === null) {
return []; // should I just use as any?
}
return Array.isArray(value) ? value : [value];
}
const x1: number[] = ensureArray(1)
const x2: number[] = ensureArray([1, 2])
const x3: string[] = ensureArray('str' as string | null)