typescript/prefer-nullish-coalescing Pedantic
무엇을 수행합니까?
null 또는 undefined일 수 있는 왼쪽 피연산자가 있는 경우, 논리적 OR(||) 또는 조건식 대신 nullish coalescing 연산자(??) 사용을 강제합니다.
왜 좋지 않은가요?
|| 연산자는 왼쪽 피연산자가 어떤 거짓 값(false, 0, '', null, undefined, NaN)인 경우 오른쪽 피연산자를 반환합니다. 이는 null 또는 undefined에만 기본값을 제공하고자 할 때 예기치 않은 동작을 유발할 수 있습니다.
nullish coalescing 연산자(??)는 왼쪽 피연산자가 null 또는 undefined인 경우에만 오른쪽 피연산자를 반환하므로 의도가 더 명확해지고 다른 거짓 값을 포함하는 버그를 피할 수 있습니다.
예시
이 규칙에 잘못된 코드 예시:
declare const x: string | null;
// ??가 더 적절한 경우 || 사용
const foo = x || "default";
// ??를 사용할 수 있는 삼항 연산자
const bar = x !== null && x !== undefined ? x : "default";
const baz = x != null ? x : "default";
// ??를 사용할 수 있는 if 문
let value = "default";
if (x !== null && x !== undefined) {
value = x;
}이 규칙에 올바른 코드 예시:
declare const x: string | null;
// nullish coalescing 사용
const foo = x ?? "default";
// 거짓 값 행동을 원할 경우 ||는 괜찮습니다
declare const y: string;
const bar = y || "default";
// 부울 타입 전환 (다음 설정으로 무시 가능: ignoreBooleanCoercion)
const bool = Boolean(x || y);구성
이 규칙은 다음 속성을 가진 구성 객체를 수용합니다.
ignoreBooleanCoercion
type: boolean
기본값: false
Boolean 생성자 인수를 무시할지 여부.
ignoreConditionalTests
type: boolean
기본값: true
조건 테스트 내부에 위치한 경우를 무시할지 여부.
ignoreIfStatements
type: boolean
기본값: false
nullish coalescing 연산자로 간단히 처리할 수 있는 모든 if 문을 무시할지 여부.
ignoreMixedLogicalExpressions
type: boolean
기본값: false
&&와 함께 사용되는 혼합 논리 표현식의 일부인 논리적 표현식을 무시할지 여부.
ignorePrimitives
type: boolean
JSON에서 ignorePrimitives가 지정될 수 있는 다양한 방식을 나타냅니다. 다음과 같습니다:
true- 모든 기본 타입 무시- 무시할 기본 타입을 지정하는 객체
ignoreTernaryTests
type: boolean
기본값: false
nullish coalescing 연산자로 단순화할 수 있는 모든 삼항 표현식을 무시할지 여부.
사용 방법
구성 파일 또는 CLI를 통해 이 규칙을 활성화하려면 다음을 사용하세요:
{
"rules": {
"typescript/prefer-nullish-coalescing": "error"
}
}oxlint --type-aware --deny typescript/prefer-nullish-coalescing