大网数据广告活动
Web 标准与前端开发

SyntaxError: new keyword cannot be used with an optional chain

· 52CE 我爱测

The JavaScript exception "new keyword cannot be used with an optional chain" occurs when the constructor of a new expression is an optional chain, or if there's an optional chain between the constructor and the parenthesized list of arguments.

The JavaScript exception "new keyword cannot be used with an optional chain" occurs when the constructor of a new expression is an optional chain, or if there's an optional chain between the constructor and the parenthesized list of arguments.

Message

SyntaxError: Invalid optional chain from new expression (V8-based)
SyntaxError: new keyword cannot be used with an optional chain (Firefox)
SyntaxError: Cannot call constructor in an optional chain. (Safari)

Error type

SyntaxError

What went wrong?

There are two ways to get this error. The first one is if the constructor expression is an optional chain expression, like this:

new Intl?.DateTimeFormat();
Number?.[parseMethod]`Hello, world!`;

The second one is if ?. occurs between the constructor and the arguments list, like this:

new Intl.DateTimeFormat?.();

Optional new is specifically forbidden because its syntax is complicated (new with and without arguments), and the result is unclear (it would be the only case where new does not evaluate to an object value). You need to translate the optional chaining to its underlying condition (see optional chaining for more information).

const result =
  Intl.DateTimeFormat === null || Intl.DateTimeFormat === undefined
    ? undefined
    : new Intl.DateTimeFormat();

Remember that optional chaining only short-circuits within a parenthesized unit. If you parenthesize your constructor expression, the optional chaining will not cause an error, because now the constructor does not short-circuit and the result is clear (the constructor will produce undefined and then cause the new expression to throw).

new (Intl?.DateTimeFormat)(); // Throws if Intl?.DateTimeFormat is undefined

However this is a bit nonsensical anyway because optional chaining prevents errors inside the property access chain, but is then guaranteed to generate an error when calling new. You would probably still want to use a conditional check.

Note that optional chaining is only forbidden as the constructor expression. You can use optional chaining inside the argument list, or use optional chaining on the new expression as a whole.

new Intl.DateTimeFormat(navigator?.languages);
new Intl.DateTimeFormat().resolvedOptions?.();

Note that there's no needs to use ?. on the new expression itself: new a()?.b, because new is guaranteed to produce a non-nullish object value.

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。