1

What am I doing wrong here:

export function fail<a>(problem: SomeProblem): a;
export function fail<a>(message: string): a;
export function fail<a>(messageOrProblem: any): a { throw Error(); }

the compiler says:

TS2148: Build: Overload signature is not compatible with function definition.

1 Answer 1

6

The type parameters here are considered 'different' because they come from different places. You should write this like so:

export function fail<a>(problem: SomeProblem): a;
export function fail<a>(message: string): a;
export function fail(messageOrProblem: any): any { throw Error(); }

As an aside, using a generic type argument only in a return value position is sort of an anti-pattern. Since you have no way to determine what value to return based on a, it's much more accurate to return any than to return an uninferable generic type. I call this the "moving the cast" pattern:

// Bad
x = fail<string>('foo'); // This looks more typesafe than it is
// Good
x = <string>fail('foo'); // Let's be honest with ourselves
Sign up to request clarification or add additional context in comments.

1 Comment

good answer! Just a mention, using a return type to drive the generic parameter becomes important in modelling JS promises and allowing automatically inferred then chaining

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.