【发布时间】:2018-07-18 08:31:34
【问题描述】:
我有这个 TypeScript 代码,它在函数声明中使用重载。此代码按预期工作。
function identity(x: string): string;
function identity(x: number): number;
function identity(x: string | number): string | number {
return x;
}
const a = identity('foo') // string
const b = identity(1) // number
const c = identity({}) // type error (expected)
我正在尝试使用函数表达式而不是函数声明来实现等效,但是出现类型错误:
/* Type '(x: string | number) => string | number' is not assignable to type '{ (x: string): string; (x: number): number; }'.
Type 'string | number' is not assignable to type 'string'.
Type 'number' is not assignable to type 'string' */
const identity: {
(x: string): string;
(x: number): number;
} = (x: string | number): string | number => x;
我想知道如何实现重载函数但使用函数表达式的相同效果。
【问题讨论】:
-
我向 TS 团队询问过这个问题,看来不可能:github.com/Microsoft/TypeScript/issues/25761
-
我也在想同样的事情。你还在坚持那些需要重载的函数声明吗?谢谢。
标签: function typescript overloading