My function is designed to return either a number, an Error
, or a NegativeError
:
class NegativeError extends Error {
name = 'NegativeError'
}
function doThing (a: number): number | NegativeError | Error {
return a < 0 ? new NegativeError() : a === 0 ? new Error() : a
}
const done = doThing() // T | NegativeError | Error
Unfortunately, when I remove the explicit return type from the function signature, TypeScript only infers T | NegativeError
as the return type:
function doThing (a: number) {
return a < 0 ? new NegativeError() : a === 0 ? new Error() : a
}
const done = doThing() // T | NegativeError
To work around this issue, I have used a constructor function to keep the return types distinct and maintain prototypical inheritance:
function NegativeError(message: string) {
Error.call(this)
this.message = message
this.name = 'NegativeError'
}
NegativeError.prototype = Object.create(Error.prototype)
NegativeError.prototype.constructor = NegativeError
However, I find this solution not very readable and it results in the TypeScript error:
An outer value of 'this' is shadowed by this container
.
Is there a better way to make TypeScript correctly infer all return types?