简体   繁体   中英

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 ?

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 (x: number & string): number | string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM