Arrays 如何键入在Typescript中返回两个或多个字符串数组交集的递归函数?
这是我用来返回两个或多个字符串数组之间的交集的代码Arrays 如何键入在Typescript中返回两个或多个字符串数组交集的递归函数?,arrays,typescript,recursion,intersection,Arrays,Typescript,Recursion,Intersection,这是我用来返回两个或多个字符串数组之间的交集的代码 export const intersection=(列表1:string[],列表2:string[],其他列表):string[]=>{ 常量结果=[]; for(设i=0;i
export const intersection=(列表1:string[],列表2:string[],其他列表):string[]=>{
常量结果=[];
for(设i=0;i
这在JS中工作得很好。但是现在我正在将代码转换为Typescript,我想知道如何键入…otherList
参数
我得到以下错误:
您可以这样键入:
export const intersection = (list1: string[], list2: string[], ...otherLists: string[][]): string[] => {
const result = [];
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 === true) {
result.push(item1);
}
}
const firstArray = otherLists.shift();
if (firstArray) {
return intersection(result, firstArray, ...otherLists);
}
return result;
};
export const intersection=(列表1:string[],列表2:string[],其他列表:string[]):string[]=>{
常量结果=[];
for(设i=0;i
我已经更新了问题。”因为我缺少返回
类型。我建议不要自己编写交叉点。这是通用工具库lodash解决的常见“问题”。我建议你用这个。
export const intersection = (list1: string[], list2: string[], ...otherLists: string[][]): string[] => {
const result = [];
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 === true) {
result.push(item1);
}
}
const firstArray = otherLists.shift();
if (firstArray) {
return intersection(result, firstArray, ...otherLists);
}
return result;
};