확장 진단

null이 될 수 없는 값에 사용한 널 병합 연산자

이 진단은 Angular 템플릿에서 불필요하게 사용한 널 병합 연산자(??)를 감지합니다. 구체적으로는 입력값의 타입에 null이나 undefined가 포함되지 않아 null이 될 수 없는 연산을 찾습니다. 이러한 값에서는 ??의 오른쪽 피연산자가 사용되지 않습니다.

import {Component} from '@angular/core';

@Component({
  // Template displays `username` if present, falls back to 'root' if it is
  // `null` or `undefined`.
  template: `<div>{{ username ?? 'root' }}</div>`,
})
class MyComponent {
  // `username` is declared as a `string` which _cannot_ be `null` or
  // `undefined`.
  username: string = 'Angelino';
}

무엇이 문제인가요?

null이 될 수 없는 입력값에 널 병합 연산자를 사용해도 아무런 효과가 없습니다. 이는 값에 허용된 타입과 템플릿에 값을 표시하는 방식이 일치하지 않는다는 뜻입니다. 개발자는 어떤 경우에는 널 병합 연산자의 오른쪽 값이 표시된다고 생각할 수 있지만, 실제로는 표시되지 않습니다. 이로 인해 프로그램의 예상 출력에 혼동이 생길 수 있습니다.

어떻게 해결하나요?

템플릿과 선언한 타입이 일치하도록 수정하세요. 입력값의 타입을 다시 확인하고 실제로 null이 될 수 있어야 하는지 확인하세요.

입력값이 null이 될 수 있어야 한다면 타입에 null 또는 undefined를 추가하여 이를 나타내세요.

import {Component} from '@angular/core';

@Component({
  template: `<div>{{ username ?? 'root' }}</div>`,
})
class MyComponent {
  // `username` is now nullable. If it is ever set to `null`, 'root' will be
  // displayed.
  username: string | null = 'Angelino';
}

입력값이 null이 될 수 없어야 한다면 TypeScript가 해당 값이 항상 null이 아님을 보장하므로 ?? 연산자와 오른쪽 피연산자를 삭제하세요.

import {Component} from '@angular/core';

@Component({
  // Template always displays `username`, which is guaranteed to never be `null`
  // or `undefined`.
  template: `<div>{{ username }}</div>`,
})
class MyComponent {
  username: string = 'Angelino';
}

필수 설정

확장 진단이 발생하려면 strictTemplates를 활성화해야 합니다. nullishCoalescingNotNullable 진단이 발생하려면 strictNullChecks도 활성화해야 합니다.

이 상황을 피할 수 없다면 어떻게 하나요?

프로젝트의 tsconfig.json 파일을 수정하여 이 진단을 비활성화할 수 있습니다.

{
  "angularCompilerOptions": {
    "extendedDiagnostics": {
      "checks": {
        "nullishCoalescingNotNullable": "suppress"
      }
    }
  }
}

자세한 내용은 확장 진단 설정을 참고하세요.