如何在TypeScript中使用第二个可选参数来缩小重载函数的类型?

7y4bm7vi  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(123)

给定一个重载函数,其中第一个参数可以是两种类型,而第二个参数只存在于其中一个变体中,那么当我们检查第一个参数的类型时,如何让编译器满意呢?
以下是我尝试过的方法和不起作用的方法。这里有一个Playground的链接

declare const bar: (input: string, extra: string) => boolean;
declare const baz: (input: string[]) => boolean;

export function foo(input: string[]): boolean;
export function foo(input: string, extra: string): boolean;
export function foo(input: string | string[], extra?: string): boolean {
  if (typeof input === 'string') {
    // ERROR: (parameter) extra: string | undefined
    return bar(input, extra);
  }

  return baz(input);
}

export function foo1(input: string[]): boolean;
export function foo1(input: string, extra: string): boolean;
export function foo1(input: string | string[], extra?: string): boolean {
  if (typeof input === 'string' && extra) {
    return bar(input, extra);
  }

  // ERROR: (parameter) input: string | string[]
  return baz(input);
}

export function foo2(input: string[]): boolean;
export function foo2(input: string, extra: string): boolean;
export function foo2(input: string | string[], extra?: string): boolean {
  if (typeof input === 'string') {
    // This works but it's unnecessarily verbose
    if (extra) {
      return bar(input, extra);
    }
    throw new Error('Unable to reach here');
  }

  return baz(input);
}
5vf7fwbs

5vf7fwbs1#

像这样?

export function foo1(input: string[]): boolean;
export function foo1(input: string, extra: string): boolean;
export function foo1(input: string | string[], extra?: string): boolean {
  if (typeof input === 'string' && extra) {
    return bar(input, extra);
  }

  // If we get here it could be input is still string, and extra is undefined say.
  // Or input is array and extra is either undefined or string
  // So we need one more check to check type of input
  
  if(Array.isArray(input)) baz(input);

  return false; // we need default
}

相关问题