Typescript: ReturnType of overloaded function

前端 未结 3 793
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 12:38

The type given by ReturnType seems to depend on the order the overload signatures are written

function applyChanges1(input: string): number
func         


        
3条回答
  •  天涯浪人
    2020-11-29 12:40

    This is a known limitation. The TypeScript team's recommendation is to include a "most general" overload signature as your last overload signature, e.g.:

    function applyChanges1(input: string): number
    function applyChanges1(input: number): string
    function applyChanges1(input: number | string): number | string
    function applyChanges1(input: number | string): number | string {
      return typeof input === "number" ? input.toString() : input.length
    }
    

    Titian Cernicova-Dragomir has a nicer alternate solution in his answer.

提交回复
热议问题