typescript/restrict-plus-operands 細かい
何をするか
このルールは、加算の両方のオペランドが同じ型であり、かつ number、string、または any であることを要求します。
なぜ問題なのか
JavaScript の + 演算子は、数値の加算と文字列の連結の両方に使用できます。オペランドが異なる型の場合、JavaScript の型変換ルールにより予期しない結果になることがあります。このルールは、両方のオペランドが互換性のある型であることを要求することで、こうした問題を回避します。
例
このルールに対して不正なコードの例:
ts
declare const num: number;
declare const str: string;
declare const bool: boolean;
declare const obj: object;
// 異なる型の混合
const result1 = num + str; // number + string
const result2 = str + bool; // string + boolean
const result3 = num + bool; // number + boolean
const result4 = obj + str; // object + string
// 異なる型のリテラル
const result5 = 42 + "hello"; // number literal + string literal
const result6 = true + 5; // boolean literal + number literalこのルールに対して正しいコードの例:
ts
declare const num1: number;
declare const num2: number;
declare const str1: string;
declare const str2: string;
// 同じ型
const sum = num1 + num2; // number + number
const concat = str1 + str2; // string + string
// 明示的な型変換
const result1 = num1 + String(num2); // まず文字列に変換
const result2 = String(num1) + str1; // まず文字列に変換
const result3 = Number(str1) + num1; // まず数値に変換
// テンプレートリテラルによる文字列連結
const result4 = `${num1}${str1}`; // 文字列連結の意図が明確
// 同じ型のリテラル
const numResult = 42 + 58; // number + number
const strResult = "hello" + "world"; // string + string設定
このルールは以下のプロパティを持つ設定オブジェクトを受け入れます。
allowAny
type: boolean
default: true
プラス演算で any 型を許可するかどうか。
allowBoolean
type: boolean
default: true
プラス演算で boolean 型を許可するかどうか。
allowNullish
type: boolean
default: true
プラス演算で null や undefined のような曖昧な型(nullish types)を許可するかどうか。
allowNumberAndString
type: boolean
default: true
プラス演算で数値と文字列の混在したオペランドを許可するかどうか。
allowRegExp
type: boolean
default: true
プラス演算で RegExp 型を許可するかどうか。
skipCompoundAssignments
type: boolean
default: false
複合代入(例:a += b)をスキップするかどうか。
使用方法
このルールを設定ファイルまたは CLI で有効化するには、次のように使用できます:
json
{
"rules": {
"typescript/restrict-plus-operands": "error"
}
}bash
oxlint --type-aware --deny typescript/restrict-plus-operands