tighten_type_of_initializing_formals 진단: non-null을 강제할 때는 assert 대신 타입 애너테이션으로

tighten_type_of_initializing_formals 진단: non-null을 강제할 때는 assert 대신 타입 애너테이션으로

분석기가 내보내는 진단에는 이름이 있어요. tighten_type_of_initializing_formals생성자의 초기화 리스트에서 assert를 써서 필드를 non-null 값으로만 초기화하려 할 때 Dart 분석기가 알려주는 린트(lint) 진단이에요. 타입 시스템으로 잡을 수 있는 문제를 assert로 잡으려 할 때 발생하는데, 타입 애너테이션을 쓰는 편이 더 깔끔하고 안전해요.

출처: tighten_type_of_initializing_formals 진단

본문

설명

분석기는 생성자의 초기화 리스트에서 assert를 써서 필드를 non-null 값으로만 초기화하려고 할 때 이 진단을 만들어요.

예시

다음 코드는 assert를 써서 타입 시스템이 잡아낼 수 있는 오류를 잡으려 하기 때문에 이 진단을 만들어요.

class C {
  final String? s;

  C(this.s) : assert(s != null);
}

흔한 해결 방법

assert를 제거하고 초기화 형식 매개변수(initializing formal) 앞에 non-nullable 타입을 붙여요.

class C {
  final String? s;

  C(String this.s);
}

더 알아보기