我有这个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;
我想知道如何实现重载但具有函数表达式的功能。
答案 0 :(得分:0)
您可以在函数实现上使用类型断言。在一项作业中,检查的兼容性更加严格,但断言它们比较弱。尽管如此,我们仍然获得了不错的类型安全性(我不确定它是否等同于实现签名检查的重载,但看起来非常接近):
//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;
};