typescript 无法从函数并集推断类型

问题描述 投票:0回答:1

我在这里缺少什么?

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

那样明确
typescript
1个回答
0
投票

我真的没有看到用例,除非你试图超载你的函数;

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
© www.soinside.com 2019 - 2024. All rights reserved.