SyntaxError: tagged template cannot be used with optional chain

帶標籤的模板字面量的標籤表示式是可選鏈,或者標籤和模板之間存在可選鏈時,會發生 JavaScript 異常“帶標籤的模板不能與可選鏈一起使用”。

訊息

SyntaxError: Invalid tagged template on optional chain (V8-based)
SyntaxError: tagged template cannot be used with optional chain (Firefox)
SyntaxError: Cannot use tagged templates in an optional chain. (Safari)

錯誤型別

SyntaxError

哪裡出錯了?

有兩種情況會引發此錯誤。第一種是標籤表示式是一個可選連結串列達式,如下所示:

js
String?.raw`Hello, world!`;
console.log?.()`Hello, world!`;
Number?.[parseMethod]`Hello, world!`;

第二種是 ?. 出現在標籤和模板之間,如下所示:

js
String.raw?.`Hello, world!`;

明確禁止在標籤中使用可選鏈,因為這樣做沒有很好的用例,並且預期的結果不清楚(它應該是 undefined 還是模板的值,就像它是未帶標籤的一樣?)。你需要將可選鏈轉換為其底層條件(有關更多資訊,請參閱可選鏈)。

js
const result =
  String.raw === null || String.raw === undefined
    ? undefined
    : String.raw`Hello, world!`;

請記住,可選鏈只在括號單元內短路。如果你將標籤表示式用括號括起來,可選鏈不會導致錯誤,因為現在標籤不會短路,結果也很清楚(標籤將產生 undefined,然後導致帶標籤的模板丟擲錯誤)。

js
(console?.log)`Hello, world!`; // Throws if console?.log is undefined

然而,這在某種程度上是無意義的,因為可選鏈阻止了屬性訪問鏈中的錯誤,但隨後在呼叫模板標籤時必然會生成錯誤。你可能仍然希望使用條件檢查。

請注意,可選鏈僅作為標籤表示式被禁止。你可以在嵌入式表示式中使用可選鏈,或者在整個帶標籤的模板表示式上使用可選鏈。

js
console.log`Hello, ${true.constructor?.name}!`; // ['Hello, ', '!', raw: Array(2)] 'Boolean'
console.log`Hello`?.toString(); // undefined

另見