打字稿中的函数类型重载 [英] Overloaded function type in typescript

查看:63
本文介绍了打字稿中的函数类型重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不提供具体函数的情况下创建重载的函数类型? 通过检查重载函数的类型,似乎可以使用接口/对象类型上的多个调用签名:

How can I create a function type, without providing a concrete function, that is overloaded? By inspecting the type of an overloaded function, it seems multiple call signatures on an interface/object type are the way to go:

function a(input: string): string
function a(input: number): number
function a(input: string | number): string | number {
  return input
}

type A = typeof a

type B = {
  (input: string): string
  (input: number): number
}

const b: B = a // Okay!

用联合类型定义相同的想法(无需使烦人的重载情况令人满意),也行得通,类型在两个方向上都是兼容的!

Defining the same idea with a union type (without that pesky catch-all case that you need to make overloads happy) also works, the types are compatible in both directions!

type C = ((input: number) => number) & ((input: string) => string)

const c: C = b // Okay!

const a2: A = c // Okay too!

但是,现在我该如何制作适合该类型的函数?我是否也必须使用重载?

But how do I now make a function fitting this type? Do I have to necessarily also use overloading?

const x: A = (input: string | number) => input

const y: A = (input: string | number) => {
  if (typeof input === "number") return input
  if (typeof input === "string") return input
  throw "excrement"
}

均失败,并出现以下完全相同的错误:

both fail with the exact same following error:

Type '(input: string | number) => string | number' is not assignable to type '{ (input: string): string; (input: number): number; }'.
  Type 'string | number' is not assignable to type 'string'.
    Type 'number' is not assignable to type 'string'.

最糟糕的是,即使我使用可读性较低的联合类型C

Worst of all, this happens even if I use the less readable union type C

Type '(input: string | number) => string | number' is not assignable to type 'C'.
  Type '(input: string | number) => string | number' is not assignable to type '(input: number) => number'.
    Type 'string | number' is not assignable to type 'number'.
      Type 'string' is not assignable to type 'number'.

希望我正在做一些明显的错误,并且有一个简单的解决方法. 否则,当我需要传递到某个地方的函数处理具有相应返回类型的多个调用签名时,最好的选择是什么?

Hopefully, I am doing something obvious wrong and there's an easy fix. Else, what are my best options when I need to demand that a function that is passed somewhere handle several call signatures with corresponding return types?

推荐答案

要定义具有多个呼叫签名的功能,如果您无法编写可分配给所需的所有呼叫签名的单个呼叫签名,则可以将必须使用重载(对于调用签名与实现签名的兼容性,它具有较宽松的规则)或类型声明.您什么都不会错过.

To define a function with multiple call signatures, if you're not able to write a single call signature that is assignable to all the call signatures you want, you will have to use either overloading (which has looser rules for compatibility of the call signatures with the implementation signature) or a type assertion. You aren't missing anything.

这篇关于打字稿中的函数类型重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆