我在这里缺少什么?
type HandlerA = (firstArg: string) => number;
type HandlerB = (firstArg: string, secondArg: number) => string;
type Handler = HandlerA | HandlerB
// works
const testA: Handler = (a, b) => 'text'
// fails, bc a is implicitly of type 'any'
const testB: Handler = (a) => 10
如您所见,testB无法推断出HandlerA。有没有办法解决这个问题而不像
const testC: Handler = (a: string) => 10
那样明确
我真的没有看到用例,除非你试图超载你的函数;
function handler(firstArg: string): string
function handler(firstArg: string, secondArg: number): string
function handler(firstArg: string, secondArg?: number): string | number {
if (!!firstArg && !secondArg) {
return 'implementation a'
}
return 'implementation b'
}
或者简单地定义一个更通用的处理程序类型
type Handler = (firstArg: string, secondArg?: number) => string | number;
const testA: Handler = (a, b) => 'text'
const testB: Handler = (a) => 10