Skip to content
← Back to rules

typescript/restrict-plus-operands Pedantic

💭 This rule requires type information.

작동 방식

이 규칙은 덧셈 연산의 두 피연산자가 동일한 타입이어야 하며, 숫자, 문자열 또는 any 타입이어야 한다고 요구합니다.

왜 문제가 되는가?

자바스크립트의 + 연산자는 숫자 덧셈과 문자열 연결 모두에 사용할 수 있습니다. 피연산자가 서로 다른 타입인 경우, 자바스크립트의 타입 강제 변환 규칙으로 인해 예상치 못한 결과가 발생할 수 있습니다. 이 규칙은 두 피연산자가 호환 가능한 타입이어야 함을 요구함으로써 이러한 문제를 방지합니다.

예시

이 규칙에 잘못된 코드 예시:

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

기본값: true

  • 연산에서 any 타입을 허용할지 여부.

allowBoolean

type: boolean

기본값: true

  • 연산에서 boolean 타입을 허용할지 여부.

allowNullish

type: boolean

기본값: true

  • 연산에서 null 또는 undefined 같은 비정형 타입을 허용할지 여부.

allowNumberAndString

type: boolean

기본값: true

  • 연산에서 숫자와 문자열의 혼합 피연산자를 허용할지 여부.

allowRegExp

type: boolean

기본값: true

  • 연산에서 RegExp 타입을 허용할지 여부.

skipCompoundAssignments

type: boolean

기본값: false

복합 할당문(예: a += b)을 건너뛸지 여부.

사용 방법

이 규칙을 구성 파일 또는 CLI를 통해 활성화하려면 다음과 같이 사용할 수 있습니다:

json
{
  "rules": {
    "typescript/restrict-plus-operands": "error"
  }
}
bash
oxlint --type-aware --deny typescript/restrict-plus-operands

참고 자료