Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare that a method throws error in typescript?

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(); }
like image 706
U Avalos Avatar asked Dec 23 '15 16:12

U Avalos


1 Answers

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.

like image 107
Max Bendick Avatar answered Oct 25 '22 08:10

Max Bendick