我在这里做错了什么:
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.
答案 0 :(得分:5)
这里的类型参数被认为是“不同的”,因为它们来自不同的地方。你应该这样写:
export function fail<a>(problem: SomeProblem): a;
export function fail<a>(message: string): a;
export function fail(messageOrProblem: any): any { throw Error(); }
另外,仅在返回值位置使用泛型类型参数是一种反模式。由于您无法根据a
确定要返回的值,因此返回any
比返回不可更改的泛型类型要准确得多。我称之为“移动演员”模式:
// Bad
x = fail<string>('foo'); // This looks more typesafe than it is
// Good
x = <string>fail('foo'); // Let's be honest with ourselves