Skip to content
← Back to rules

typescript/no-unsafe-unary-minus 정확성

This rule is turned on by default when type-aware linting is enabled.
💭 This rule requires type information.

작동 방식

이 규칙은 'number' | 'bigint' 타입이 아닌 값에 일항 뺄셈 연산자(-)를 사용하는 것을 금지합니다.

왜 좋지 않은가?

일항 뺄셈 연산자는 숫자 값에만 사용해야 합니다. 다른 타입에 사용할 경우, 자바스크립트의 타입 강제 변환 규칙으로 인해 예기치 못한 동작이 발생할 수 있습니다.

예시

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

ts
declare const value: any;
const result1 = -value; // any에 대해 안전하지 않음

declare const str: string;
const result2 = -str; // string에 대해 안전하지 않음

declare const bool: boolean;
const result3 = -bool; // boolean에 대해 안전하지 않음

declare const obj: object;
const result4 = -obj; // object에 대해 안전하지 않음

declare const arr: any[];
const result5 = -arr; // array에 대해 안전하지 않음

이 규칙에 올바른 코드 예시:

ts
declare const num: number;
const result1 = -num; // 안전함

declare const bigint: bigint;
const result2 = -bigint; // 안전함

const literal = -42; // 안전함

const bigintLiteral = -42n; // 안전함

declare const union: number | bigint;
const result3 = -union; // 안전함

// 필요하다면 먼저 숫자로 변환
declare const str: string;
const result4 = -Number(str); // 안전한 변환

사용 방법

구성 파일 또는 명령줄에서 이 규칙을 활성화하려면 다음을 사용하세요:

json
{
  "rules": {
    "typescript/no-unsafe-unary-minus": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-unsafe-unary-minus

참고 자료