gpt4 book ai didi

exception - typescript 2 - 在三元/条件运算符表达式中抛出

转载 作者:行者123 更新时间:2023-12-04 12:13:50 24 4
gpt4 key购买 nike

我尝试编译:

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

...并在 throw 上收到错误消息- expression expected .我可以使用就地调用的内联方法解决这个问题,但这看起来不太好。 ( (() => {throw Error("bad things"})() )

为什么不能放入三元运算符的分支?或者是否有另一种有效的语法,也许是我缺少的编译选项?

在变通方法( (() => throw Error("bad things")() )中,如果函数体中没有大括号,抛出似乎也不起作用。

最佳答案

这是该语言的语法怪癖。

声明throw ex可以看作是类型为 never 的表达式, 因为 never是不返回的函数类型,这正是您 throw 时发生的情况。 .在许多语言中都有 bottom type (什么是 never 的技术术语——它不仅仅是一个“奇怪的关键字”)。

声明throw ex例如,不同于语句 for (let x of ...)因为后者不能被理解为返回任何东西,而 throw ex可以理解为返回never .

关于exception - typescript 2 - 在三元/条件运算符表达式中抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40573516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com