如何在 Typescript 中指定一个表示 2 个函数联合的类型

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

假设我有 2 个函数

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

我想创建另一个仅接受 functionAfunctionB 作为输入的函数,例如

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

Typescript 中是否有一种方法可以指定仅表示 functionAfunctionB 的类型?

您不能为特定函数创建类型。 functionA 是一个值而不是类型。但是,您可以这样做:

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

函数以稍微不直观的方式组合在一起。 FuncEither 将是 (x: number & string): number | string