Search code examples
typescripttype-definition

How to specify a type in Typescript which represents the union of 2 functions


Let's suppose that I have 2 function

export const functionA = () => {// do stuff}
export const functionB = () => {// do stuff}

and I want to create another function that accepts as input only either functionA or functionB, for instance

export const anotherFunction = functionAorB => {// do stuff }

Is there a way in Typescript to specify a type representing only either functionA or functionB?


Solution

  • You can't make a type on a specific function. functionA is a value not a type. However, you can do:

    type FuncA = (x: number) => number;
    type FuncB = (x: string) => string;
    type FuncEither = FuncA | FuncB;
    

    Functions combine in slightly unintuitive ways. FuncEither will be (x: number & string): number | string