避免不必要的範本表達式
禁止不必要的範本表達式。
🔒
擴充 "plugin:@typescript-eslint/strict-type-checked"
在 ESLint 設定檔 中啟用此規則。
🔧
此規則報告的一些問題可由以下方法自動修復: --fix
ESLint 命令列選項.
💭
此規則需要 類型資訊 才能執行。
此規則會報告包含替換表達式(也稱為嵌入式表達式或字串內插)的範本文字,這些表達式是不必要的,可以簡化。
從
no-useless-template-literals
遷移此規則以前稱為 no-useless-template-literals
。我們建議使用者改用新名稱 no-unnecessary-template-expression
,因為未來版本會移除 typescript-eslint 中的舊名稱。
新名稱會直接替換過去的名稱,具備相同功能。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-template-expression": "error"
}
};
在遊樂場中嘗試此規則 ↗
範例
- ❌ 不正確
- ✅ 正確
// Static values can be incorporated into the surrounding template.
const ab1 = `${'a'}${'b'}`;
const ab2 = `a${'b'}`;
const stringWithNumber = `${'1 + 1 = '}${2}`;
const stringWithBoolean = `${'true is '}${true}`;
// Some simple expressions that are already strings
// can be rewritten without a template at all.
const text = 'a';
const wrappedText = `${text}`;
declare const intersectionWithString: string & { _brand: 'test-brand' };
const wrappedIntersection = `${intersectionWithString}`;
在遊樂場中開啟// Static values can be incorporated into the surrounding template.
const ab1 = `ab`;
const ab2 = `ab`;
const stringWithNumber = `1 + 1 = 2`;
const stringWithBoolean = `true is true`;
// Some simple expressions that are already strings
// can be rewritten without a template at all.
const text = 'a';
const wrappedText = text;
declare const intersectionWithString: string & { _brand: 'test-brand' };
const wrappedIntersection = intersectionWithString;
在遊樂場中開啟資訊
此規則並不是針對沒有用替代運算式書寫一般字串的範本字面值進行標記。也就是說,此規則不會協助您將 `this`
轉成 "this"
。如果您要尋找具有這種功能的規則,則您可以設定 @stylistic/ts/quotes
規則來進行設定。
選項
此規則無法設定。
不適合使用的時機
當您允許將字串運算式寫入範本字面值時。
相關
經過類型檢查的程式碼審查規則較傳統的程式碼審查規則強大,但需要設定 經過類型檢查的程式碼審查。如果您啟用經過類型檢查的程式碼審查規則後,效能出現下降,請參閱 效能問題排除。