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")()
).
You can't throw an exception in a ternary clause. Both options must return a value, which throw new Exception(); doesn't satisfy.
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.
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.
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.
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
.
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