Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 throw - 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")()).

like image 509
Jørgen Tvedt Avatar asked Nov 13 '16 11:11

Jørgen Tvedt


People also ask

Can we use Throw in ternary operator?

You can't throw an exception in a ternary clause. Both options must return a value, which throw new Exception(); doesn't satisfy.

How do you write 3 conditions in a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Can ternary operator have two conditions?

In the above syntax, we have tested 2 conditions in a single statement using the ternary operator. In the syntax, if condition1 is incorrect then Expression3 will be executed else if condition1 is correct then the output depends on the condition2.

How do you break a statement in a ternary operator?

The ?: ternary operator produces a value, and all three of its operands are expressions. break is a statement, not an expression. It does not produce a value.


1 Answers

It's a syntactic quirk of the language.

The statement throw ex can be regarded as an expression that has the type never, because never is the type of functions that don't return, which is exactly what happens when you throw. In many languages that have a bottom type (the technical term for what never is -- it's not merely an "odd keyword").

The statement throw ex is different from, for example, the statement for (let x of ...) because the latter cannot be understood to return anything, whereas throw ex can be understood to return never.

like image 77
GregRos Avatar answered Sep 28 '22 02:09

GregRos