The following doesn't compile with error "a function whose declared type is neither void nor any must return a value or consist of a single throw statement".
Is there a way to make the compiler recognize that _notImplemented throws an exception?
function _notImplemented() {
throw new Error('not implemented');
}
class Foo {
bar() : boolean { _notImplemented(); }
The only woraround I can see is to use generics. But it seems kind of hacky. Is there a better way?
function _notImplemented<T>() : T {
throw new Error('not implemented');
}
class Foo {
bar() : boolean { return _notImplemented(); }
You can use an Either rather than a throw.
An Either is a structure that typically holds either an error or a result. Because it is a type like any other, TypeScript can easily utilize it.
Ex:
function sixthCharacter(a: string): Either<Error, string> {
if (a.length >= 6) {
return Either.right<Error, string>(a[5]);
}
else {
return Either.left<Error, string>(new Error("a is to short"));
}
}
A function that utilizes the function sixthCharacter
may choose to unwrap it, return a maybe itself, throw an error itself, or other options.
You'll need to select a library that has an Either in it - take a look at monad libraries like TsMonad or monet.js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With