给定一个重载函数,其中第一个参数可以是两种类型,而第二个参数只存在于其中一个变体中,那么当我们检查第一个参数的类型时,如何让编译器满意呢?
以下是我尝试过的方法和不起作用的方法。这里有一个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);
}
1条答案
按热度按时间5vf7fwbs1#
像这样?