TypeScript:函数表达式重载



我有这个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;

我想知道如何使用函数表达式来实现重载函数的效果。

您可以在函数实现上使用类型断言。在赋值中,兼容性检查更严格,而断言则更弱。尽管如此,我们仍然获得了相当多的类型安全性(我不确定它是否等同于实现签名检查的过载,但它似乎非常接近(:

//OK
const identity = ((x: string | number): string | number => x) as {
(x: string): string;
(x: number): number;
};
// Error argument is incompatible
const identity2 = ((x: boolean): string | number => x) as {
(x: string): string;
(x: number): number;
};
// Error return type is incompatible 
const identity3 = ((x: string | number) => false) as {
(x: string): string;
(x: number): number;
};

最新更新