如何为接收任意数组的函数正确添加TypeScript类型并实现类型提示?
用TypeScript泛型实现任意数组的类型提示,以及你的函数类型标注方案
为什么map、filter能给任意数组做类型提示?
map、filter这类数组方法靠TypeScript泛型实现灵活的类型约束。泛型允许函数接收任意类型的参数,同时保留类型信息,不用硬写死any。比如原生Array.prototype.map的核心类型逻辑是:
interface Array<T> { map<U>(callback: (item: T) => U): U[]; }
这里T是原数组元素的类型,U是回调返回值的类型——不管你传入number[]还是string[],TS都会自动推断T,再根据回调的返回值推断U,最终给出准确的返回数组类型提示。
给你的utils_process_sequential函数加类型标注
我们用泛型替换所有any,让函数既能接收任意类型的数组,又能提供完整的类型提示:
function utils_process_sequential<T, U>( array: T[], task: (item: T) => Promise<U> | U ): Promise<U[]> { return new Promise(async (rs, rj) => { const result: U[] = []; async function next(index: number = 0): Promise<void> { try { const res = await task(array[index]); res !== undefined && result.push(res); index < array.length - 1 ? await next(++index) : rs(result); } catch (err) { rj({ error: 'utils_process_sequential', message: 'error processing task' }); } } array.length ? await next() : rs([]); }); }
标注说明:
<T, U>:声明两个泛型参数,T代表输入数组的元素类型,U代表任务函数返回值的类型(也就是最终结果数组的元素类型)array: T[]:约束输入数组的元素类型为Ttask: (item: T) => Promise<U> | U:任务函数接收T类型的元素,返回值可以是同步的U或者异步的Promise<U>,兼容同步/异步任务场景Promise<U[]>:明确函数返回的是U类型数组的Promise
使用示例
调用时TS会自动推断泛型类型,不用手动指定:
// 输入number数组,任务返回string类型 const numList = [1, 2, 3]; const processedList = await utils_process_sequential(numList, async (num) => { return `Number: ${num}`; }); // processedList的类型自动推断为Promise<string[]>
内容的提问来源于stack exchange,提问作者user21978638
相关产品推荐
相关产品推荐

