TypeScript中如何为多数组交集递归函数的...otherLists参数标注类型
解决TypeScript中多字符串数组交集函数的剩余参数类型问题
你碰到的类型错误核心是...otherLists参数缺少明确的TypeScript类型标注,默认情况下TS会把它推断为any[],这就触发了类型检查的报错。咱们来一步步修正这个问题,同时让函数的类型更严谨。
修正后的字符串数组交集函数
首先针对你需求的字符串数组场景,给剩余参数加上正确的类型标注:
export const intersection = (list1: string[], list2: string[], ...otherLists: string[][]): string[] => { const result: string[] = []; for (let i = 0; i < list1.length; i++) { const item1 = list1[i]; let found = false; for (let j = 0; j < list2.length && !found; j++) { found = item1 === list2[j]; } if (found) { result.push(item1); } } if (otherLists.length) { // 非空断言告诉TS:此时otherLists至少有一个元素,shift()不会返回undefined return intersection(result, otherLists.shift()!, ...otherLists); } else { return result; } };
关键类型说明
...otherLists: string[][]:剩余参数的作用是把后续传入的所有string[]类型的参数收集成一个数组,所以这个数组的每个元素都是string[],整体类型自然是string[][]。otherLists.shift()!:因为我们已经通过otherLists.length判断了数组不为空,所以shift()返回的肯定是一个有效的string[],用非空断言!可以消除TS关于“可能为undefined”的类型警告。
进阶:通用泛型版本(支持任意类型数组)
如果之后需要支持其他类型的数组交集,比如数字数组、自定义对象数组,可以改成泛型版本,让函数更通用:
export const intersection = <T>(list1: T[], list2: T[], ...otherLists: T[][]): T[] => { const result: T[] = []; for (let i = 0; i < list1.length; i++) { const item1 = list1[i]; let found = false; for (let j = 0; j < list2.length && !found; j++) { // 用Object.is代替===,能正确处理NaN、+0/-0这类特殊值的相等判断 found = Object.is(item1, list2[j]); } if (found) { result.push(item1); } } if (otherLists.length) { return intersection(result, otherLists.shift()!, ...otherLists); } else { return result; } };
这个版本可以处理任意类型的数组,比如intersection([1,2,3], [2,3,4], [3,4,5])会返回[3],非常灵活。
内容的提问来源于stack exchange,提问作者cbdeveloper
相关产品推荐
相关产品推荐

