【发布时间】:2019-02-07 11:45:49
【问题描述】:
如何在不提供具体函数的情况下创建重载的函数类型? 通过检查重载函数的类型,似乎可以在接口/对象类型上使用多个调用签名:
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!
用联合类型定义相同的想法(没有那种令人讨厌的包罗万象的情况,你需要让重载快乐)也有效,类型在两个方向上都兼容!
type C = ((input: number) => number) & ((input: string) => string)
const c: C = b // Okay!
const a2: A = c // Okay too!
但是我现在如何制作适合这种类型的函数呢?我是否也必须使用重载?
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"
}
两者都失败并出现完全相同的以下错误:
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,也会发生这种情况
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'.
希望我做错了什么,并且有一个简单的解决方法。 否则,当我需要要求在某处传递的函数处理具有相应返回类型的多个调用签名时,我最好的选择是什么?
【问题讨论】:
标签: typescript types overloading