Skip to content
← Back to rules

typescript/switch-exhaustiveness-check Pedantic

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

작동 방식

이 규칙은 유니언 타입을 기준으로 스위치 문을 사용할 때, 모든 가능한 케이스를 처리해야 함을 요구합니다.

왜 문제가 되는가?

유니언 타입을 기준으로 스위치 문을 사용할 때, 모든 가능한 경우를 처리하지 않으면 런타임 오류가 발생할 수 있습니다. TypeScript는 이를 검사할 수 있지만, 스위치 문이 올바르게 구조화되어야 하며, TypeScript가 분석할 수 있는 기본값(default) 케이스가 있어야 합니다.

예시

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

ts
type Status = "pending" | "approved" | "rejected";

function handleStatus(status: Status) {
  switch (status) {
    case "pending":
      return "승인 대기 중";
    case "approved":
      return "요청 승인됨";
    // 'rejected' 케이스 누락
  }
}

enum Color {
  Red,
  Green,
  Blue,
}

function getColorName(color: Color) {
  switch (color) {
    case Color.Red:
      return "빨간색";
    case Color.Green:
      return "초록색";
    // Color.Blue 케이스 누락
  }
}

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

ts
type Status = "pending" | "approved" | "rejected";

function handleStatus(status: Status) {
  switch (status) {
    case "pending":
      return "승인 대기 중";
    case "approved":
      return "요청 승인됨";
    case "rejected":
      return "요청 거부됨";
  }
}

// 또는 기본값 케이스를 통해 완전성 확인을 수행하는 경우
function handleStatusWithDefault(status: Status) {
  switch (status) {
    case "pending":
      return "승인 대기 중";
    case "approved":
      return "요청 승인됨";
    case "rejected":
      return "요청 거부됨";
    default:
      const _exhaustiveCheck: never = status;
      return _exhaustiveCheck;
  }
}

enum Color {
  Red,
  Green,
  Blue,
}

function getColorName(color: Color) {
  switch (color) {
    case Color.Red:
      return "빨간색";
    case Color.Green:
      return "초록색";
    case Color.Blue:
      return "파란색";
    default:
      const _exhaustiveCheck: never = color;
      return _exhaustiveCheck;
  }
}

구성

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

allowDefaultCaseForExhaustiveSwitch

type: boolean

기본값: true

완전하지 않은 스위치 문에 기본값(default) 케이스를 허용할지 여부. false로 설정 시, 기본값 케이스 없이 완전한 스위치 문을 요구합니다.

considerDefaultExhaustiveForUnions

type: boolean

기본값: false

유니언 타입에 대해 default 케이스를 완전한 것으로 간주할지 여부. true로 설정 시, 유니언 멤버들이 명시적으로 모두 처리되지 않더라도 default 케이스가 포함된 스위치 문은 완전한 것으로 간주됩니다.

defaultCaseCommentPattern

type: string

default 케이스의 주석에서 일치할 경우, 완전성 검사를 무시하는 정규 표현식 패턴입니다. 예: @skip-exhaustive-checkdefault: // @skip-exhaustive-check 허용

requireDefaultForNonUnion

type: boolean

기본값: false

완전하지 않은 유니언 타입을 기준으로 하는 스위치 문에 기본값 케이스를 요구할지 여부. true로 설정 시, 완전하지 않은 유니언 타입을 기준으로 하는 스위치 문은 반드시 기본값 케이스를 가져야 합니다.

사용 방법

이 규칙을 활성화하려면 설정 파일 또는 CLI를 사용할 수 있습니다:

json
{
  "rules": {
    "typescript/switch-exhaustiveness-check": "error"
  }
}
bash
oxlint --type-aware --deny typescript/switch-exhaustiveness-check

참고 항목