Skip to content
← Back to rules

typescript/strict-boolean-expressions Pedantic

💭 This rule requires type information.
🚧 An auto-fix is planned for this rule, but not implemented at this time.

작동 방식

부울 표현식에서 특정 타입을 사용하는 것을 금지합니다.

왜 문제가 될까요?

부울이 예상되는 표현식에서 부울이 아닌 타입의 사용을 금지합니다.
booleannever 타입은 항상 허용됩니다. 추가로 부울 컨텍스트에서 안전하다고 간주되는 타입은 옵션을 통해 구성할 수 있습니다.

다음 노드들이 검사됩니다:

  • !, &&, || 연산자의 인수
  • 조건부 표현식(cond ? x : y)의 조건
  • if, for, while, do-while 문의 조건

예시

이 규칙에 부적절한 코드 예시:

ts
const str = "hello";
if (str) {
  console.log("string");
}

const num = 42;
if (num) {
  console.log("number");
}

const obj = { foo: "bar" };
if (obj) {
  console.log("object");
}

declare const maybeString: string | undefined;
if (maybeString) {
  console.log(maybeString);
}

const result = str && num;
const ternary = str ? "yes" : "no";

이 규칙에 적절한 코드 예시:

ts
const str = "hello";
if (str !== "") {
  console.log("string");
}

const num = 42;
if (num !== 0) {
  console.log("number");
}

const obj = { foo: "bar" };
if (obj !== null) {
  console.log("object");
}

declare const maybeString: string | undefined;
if (maybeString !== undefined) {
  console.log(maybeString);
}

const bool = true;
if (bool) {
  console.log("boolean");
}

구성

이 규칙은 다음 속성을 가진 구성 객체를 수락합니다:

allowAny

type: boolean

기본값: false

부울 컨텍스트에서 any 타입을 허용할지 여부.

allowNullableBoolean

type: boolean

기본값: false

부울 컨텍스트에서 boolean | null과 같은 널 가능성 있는 부울 타입을 허용할지 여부.

allowNullableEnum

type: boolean

기본값: false

부울 컨텍스트에서 널 가능성 있는 열거형 타입을 허용할지 여부.

allowNullableNumber

type: boolean

기본값: false

부울 컨텍스트에서 number | null과 같은 널 가능성 있는 숫자 타입을 허용할지 여부.

allowNullableObject

type: boolean

기본값: true

부울 컨텍스트에서 널 가능성 있는 객체 타입을 허용할지 여부.

allowNullableString

type: boolean

기본값: false

부울 컨텍스트에서 string | null과 같은 널 가능성 있는 문자열 타입을 허용할지 여부.

allowNumber

type: boolean

기본값: true

부울 컨텍스트에서 숫자 타입을 허용할지 여부 (0이 아닌 숫자 확인).

allowString

type: boolean

기본값: true

부울 컨텍스트에서 문자열 타입을 허용할지 여부 (빈 문자열이 아닌 문자열 확인).

사용 방법

이 규칙을 구성 파일 또는 명령줄에서 활성화하려면 다음과 같이 사용할 수 있습니다:

json
{
  "rules": {
    "typescript/strict-boolean-expressions": "error"
  }
}
bash
oxlint --type-aware --deny typescript/strict-boolean-expressions

참고 자료