Typescript Union of function with other type throws error

Viewed 21

I'm trying to have a property with a union type of a function and a string.

export type IMenuItem = {
    target: string | (val1:any[], val2:number) => number;
}

TS playground sample can be accessed here.

But the TS compiler gives an error: "Function type notation must be parenthesized when used in a union type."

Is the type declared incorrectly? Or is there a workaround for this?

However, it works if we remove the union.

export type IMenuItem = {
    target: (val1:any[], val2:number) => number;
}
1 Answers

You need to wrap you function with parenthesizes

export type IMenuItem = {
    target: string | ((val1:any[], val2:number) => number);
}
Related