Jørgen Tvedt Jørgen Tvedt - 1 year ago 216
TypeScript Question

Typescript 2 - throw'ing in ternary/conditional operator expression

I try to compile:

const value = "20"
const x : string | never = "10" === value ? throw Error("bad things") : "hello"

... and get an error on
expression expected
. I can resolve this using an inline method invoked in place, but that does not look nice. (
(() => {throw Error("bad things"})()

Why is not OK to throw in a branch of the ternary operator? Or is there another syntax that works, perhaps compile options I'm missing?

Throw does not seem to work without curly brackets in the function body either, in the work-around, (
(() => throw Error("bad things")()

Answer Source

This is how many languages are constructed, you have statements and expressions. In this case you are assigning x a value, but throwing an error is not a value/expression, it's a statement/operation.

You can't do this for just the same reason why you cant write something like:

const x : string | never = "10" === value ? for(var i in myArray) { /* do stuff */ } : "hello".

It's simply against the rules of the language, even if you can "hack" around it using a self evaluation function, which theoretically evaluates and is an expression.

Check out this question for a better explanation of statements and expressions.

The never-keyword in TS is an odd type connected to their control flow analysis. It does not allow you to suddently treat statements as expressions, so if you don't want your immediately invoked function expression, you could just use a regular function:

const value = "20"
var thrower = () => { throw Error("bad things"); }
const x: string | never = "10" === value ? thrower() : "hello";

If this really is what you want to do. This would be much more readable:


if(value !== "10")
    throw Error("bad things");

const x: string = "hello";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download