prefer-string-starts-ends-with
文字列のサブストリングをチェックする他の同等のメソッドよりも、
String#startsWith
とString#endsWith
の使用を強制します。
🎨
拡張 "plugin:@typescript-eslint/stylistic-type-checked"
を ESLint設定 でこのルールを有効にします。
🔧
このルールによって報告されるいくつかの問題は、 --fix
ESLint コマンドラインオプション.
で自動的に修正できます。
💭 このルールは、 型情報
を実行するために必要です。
文字列が特定の文字列で始まるか終わるかを確認する方法は、foo.indexOf('bar') === 0
など、複数あります。ES2015以降、JavaScriptで最も一般的な方法は、String#startsWith
とString#endsWith
を使用することです。これらのメソッドを一貫して使用することで、コードの可読性が向上します。
このルールは、文字列メソッドを
String#startsWith
またはString#endsWith
で安全に置き換えることができる場合に報告します。module.exports = {
"rules": {
"@typescript-eslint/prefer-string-starts-ends-with": "error"
}
};
.eslintrc.cjs
プレイグラウンドでこのルールを試す ↗
- 例
- ❌ 不正
declare const foo: string;
// starts with
foo[0] === 'b';
foo.charAt(0) === 'b';
foo.indexOf('bar') === 0;
foo.slice(0, 3) === 'bar';
foo.substring(0, 3) === 'bar';
foo.match(/^bar/) != null;
/^bar/.test(foo);
// ends with
foo[foo.length - 1] === 'b';
foo.charAt(foo.length - 1) === 'b';
foo.lastIndexOf('bar') === foo.length - 3;
foo.slice(-3) === 'bar';
foo.substring(foo.length - 3) === 'bar';
foo.match(/bar$/) != null;
/bar$/.test(foo);
✅ 正しいdeclare const foo: string;
// starts with
foo.startsWith('bar');
// ends with
foo.endsWith('bar');
✅ 正しいプレイグラウンドで開く
オプション
type Options = [
{
/** Whether to allow equality checks against the first or last element of a string. */
allowSingleElementEquality?:
| 'never'
/** Whether to allow equality checks against the first or last element of a string. */
| 'always';
},
];
const defaultOptions: Options = [{ allowSingleElementEquality: 'never' }];
このルールは、以下のオプションを受け入れます。
allowSingleElementEquality
'always'
に切り替えた場合、このルールは、文字列の最初または最後の文字に対する等価性チェックを許可します。これは、特殊文字のエンコードを扱わず、より簡潔なスタイルを好むプロジェクトで推奨される場合があります。
declare const text: string;
text[0] === 'a';
text[0] === text[0].toUpperCase();
text[0] === text[1];
text[text.length - 1] === 'b';
✅ 正しい次のコードは、デフォルトでは不正と見なされますが、allowSingleElementEquality: 'always'
を使用すると許可されます。
使用しない場合
文字列チェックのスタイルを気にしない場合は、このルールを安全にオフにできます。ただし、一貫性のないスタイルは、プロジェクトの可読性を損なう可能性があることに注意してください。