Typescript `ensureArray` 辅助泛型类型
Typescript `ensureArray` helper generic type
我想创建一个辅助函数来确保值被包装在数组中。
- 如果值为
null
或 undefined
return 空数组
- 如果值为数组,则保持原样
- 否则将值包装在数组中
我不明白的是 typescript 抱怨什么,如何修复它以及有没有办法获得更具描述性的错误消息:
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)
您不需要条件类型!
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)
我想创建一个辅助函数来确保值被包装在数组中。
- 如果值为
null
或undefined
return 空数组 - 如果值为数组,则保持原样
- 否则将值包装在数组中
我不明白的是 typescript 抱怨什么,如何修复它以及有没有办法获得更具描述性的错误消息:
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)
您不需要条件类型!
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)