[英]Cannot overload a generic function in TypeScript
我在这里做错了什么:
export function fail<a>(problem: SomeProblem): a;
export function fail<a>(message: string): a;
export function fail<a>(messageOrProblem: any): a { throw Error(); }
编译器说:
TS2148: Build: Overload signature is not compatible with function definition.
这里的类型参数被认为是“不同的”,因为它们来自不同的地方。 您应该这样写:
export function fail<a>(problem: SomeProblem): a;
export function fail<a>(message: string): a;
export function fail(messageOrProblem: any): any { throw Error(); }
顺便说一句,仅在返回值位置使用通用类型参数是一种反模式。 既然你没有办法确定返回基于什么样的价值a
,它更准确返回any
比返回uninferable泛型类型。 我称其为“移动演员”模式:
// Bad
x = fail<string>('foo'); // This looks more typesafe than it is
// Good
x = <string>fail('foo'); // Let's be honest with ourselves
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.