Knack
Knack

Reputation: 1124

Typescript Function Parameter as Union of Set<T> and Array<T>

I'm trying to use a union type of Set and Array as function parameter:

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

However, the code does not compile. It throws the following error message:

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.

I understand that Set and Array have different methods, but both have the forEach() method, which is the only one I'm using.

Upvotes: 1

Views: 732

Answers (1)

Romain
Romain

Reputation: 810

If you use only forEach, you can just define a type like this:

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;
};

It should be compatible with the Set and Array types.

Upvotes: 2

Related Questions