函数联合的合并参数的类型

时间:2021-04-07 13:06:25

标签: typescript types

假设我们有一个给定的函数联合类型:

type UnionFunc = ((a: string, b: number) => string) | ((a: string, b: any, c: boolean) => number)

有没有办法让这个联合的参数满足联合中的所有功能?无论我们拥有的每个函数的返回类型是什么,主要的问题是获取这些参数。

MergedParameters<UnionFunc>; // [a: string, b: number, c: boolean]

另外,我想要一个适用于以下所有情况的解决方案:

// with rest parameter

MergedParameters<
  | (a: string, b: boolean) => string
  | (...args: any[]) => number
> // [a: string, b: boolean, ...any[]]

// with optional parameters

MergedParameters<
  | (a: string, b?: boolean) => string
  | (a: string, b: boolean) => number
> // [a: string, b: boolean]

MergedParameters<
  | (a: string, b: string) => string
  | (a: string, b: string, c?: string) => number
> // [a: string, b: string, c: string | undefined]

// with less precise parameters

MergedParameters<
  | (a: string, b: string) => string
  | (a: string | number, b: string) => number
> // [a: string, b: string]

// with conflicting parameters

MergedParameters<
  | (a: number, b?: boolean) => string
  | (a: string, b: boolean) => number
> // never

// with multiple functions

MergedParameters<
  | (a: string, b: number) => string
  | (a: string, b: number, c?: string) => number
  | (a: string, b: number, c: string, ...args: any[]) => number
> // [a: string, b: number, c: string, ...any[]]

TypeScript Playground

UPD:

另一个奇怪的事情是,当我声明一个返回相同类型的函数数组时,TypeScript 会以某种方式执行它。我想知道是否有办法在我的特定情况下重用它:

const funcs = [
  (a: string, b: any): any => {},
  (a: string, b: number, c?: boolean): any => {},
]

type FuncType = typeof funcs[number]; // (a: string, b: number, c?: boolean | undefined) => any

Playground with array of functions

1 个答案:

答案 0 :(得分:0)

我不知道我是否正确理解了你想要做什么。 也许下面的这个方法可以帮助你有一些想法。

type myFirstType = ((a: string, b: number) => string);
type mySecondType = ((a: string, b: any, c: boolean) => number);
type UnionFunc = myFirstType | mySecondType;


const myFunc: UnionFunc = (a: string, b: any, c:boolean): number => {
  return 1;
}

const myFunc2: UnionFunc = (a: string, b: number): string =>{
  return "1;"
}
相关问题