Typescript函数参数为Set <t>和Array <t>的并集

时间:2019-05-02 13:27:16

标签: typescript union-types

我正在尝试使用Set和Array的并集类型作为函数参数:

export function demo(
  items: Set<string> | string[]
): Set<string> {
  const allItems = new Set<string>();
  items.forEach((item: string) => {
    allItems.add(item);
  });
  return allItems;
}

但是,代码无法编译。它将引发以下错误消息:

Cannot invoke an expression whose type lacks a call signature. 
Type '((callbackfn: (value: string, value2: string, set: Set<string>) => void, thisArg?: any) => void) | ((callbackfn: (value: string, index: number, array: string[]) => void, thisArg?: any) => void)' has no compatible call signatures.

我了解Set和Array有不同的方法,但是都具有forEach()方法,这是我正在使用的唯一方法。

1 个答案:

答案 0 :(得分:2)

如果仅使用forEach,则可以定义如下类型:

type WithForEach<T> = { 
   forEach: (callbackfn: (value: T) => void) => void; 
};

export const demo = (
    items: WithForEach<string>
): Set<string> => {
    const allItems = new Set<string>();
    items.forEach((item: string) => {
        allItems.add(item);
    });
    return allItems;
};

它应该与SetArray类型兼容。