Daniel San
Daniel San

Reputation: 2026

How to enforce a function to return a value of a given type?

Maybe there is a tsconfig option to set this, but if I write something like

function codeToMsg(a: number): string {
    if (a == 200)
        return "OK";
}

let msg = codeToMsg(123456);

I don't get an error from the compiler saying that the function may not return a value of the type string (it`s now returned undefined). How could this be enforced?

Upvotes: 1

Views: 421

Answers (2)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220964

Turn on either the strictNullChecks or noImplicitReturns compiler options to cause this to be an error

Upvotes: 5

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249656

One option is to use "noImplicitReturns": true. This will issue a warning if not all code paths return a value.

Another option is to use strictNullCheck, which will cause your function to report an error, but that comes with a host of other behavior you probably don't want.

Upvotes: 2

Related Questions