为什么 ES6 箭头函数中的 `throw` 无效?

问题描述 投票:0回答:4

我只是在寻找一个原因为什么这是无效的:

() => throw 42;

我知道我可以通过以下方式绕过它:

() => {throw 42};
javascript ecmascript-6 arrow-functions
4个回答
49
投票

如果您不使用块 (

{}
) 作为箭头函数的主体,则主体必须是表达式:

ArrowFunction:
    ArrowParameters[no LineTerminator here] => ConciseBody

ConciseBody:
    [lookahead ≠ { ] AssignmentExpression
    { FunctionBody }

但是

throw
是一个陈述,而不是一个表达式。


理论上

() => throw x;

相当于

() => { return throw x; }

这也无效。


5
投票

你不能

return throw
这实际上就是你想要做的:

function(){
  return throw 42;
}

3
投票

如果在箭头函数中省略大括号,则会创建 隐式返回,这相当于使用大括号创建显式返回,如下所示:

() => { return throw 42 };

但是,您只能返回表达式,而不能返回语句

throw
是一个声明。


0
投票

要破解,您可以使用函数包装

throw
。然后将其用作表达式的一部分。

function explode (str?: string) { throw new Error(str) };
const oups = () => explode("42");
oups();
function explode (str?: string) { throw new Error(str) };
const input: null | number = null;
const output = (input ?? explode("input should not be null")) + 42;
© www.soinside.com 2019 - 2024. All rights reserved.