Frontend/Angular

앵귤러 Property has no initializer and is not definitely assigned in the constructor 오류 해결

컴슈터 2024. 3. 20. 07:52

문제 발생

앵귤러에서 클래스 안에서 속성 선언 시 아래의 오류가 발생한다.

Property xxx has no initializer and is not definitely assigned in the constructor

name이라는 문자열과 todos라는 배열을 선언할 때, 속성 값에 초기화 값이 없다는 뜻이다. 속성을 선언하고 난 뒤 값을 할당하거나 생성자에 초기화하지 않을 때 발생한다. 이 오류는 TypeScript의 엄격한 클래스 초기화 검사의 일부로, 모든 클래스 속성이 사용되기 전에 초기화되는지 확인한다.

해결 방법 1

속성 값을 직접 선언하여 초기화한다. 

  name: string = ''; // 빈 문자열로 초기화
  
  todos: {
    done: boolean,
    text: string;
  }[] = []; // 빈 배열로 초기화

  constructor() {
  }

해결 방법 2

생성자(constructor)에서 속성을 초기화한다.

  name: string;
  
  todos: {
    done: boolean,
    text: string;
  }[];

  constructor() { // 생성자에서 속성 초기화
    this.name = '테스트';
    this.todos = [
      { done: false, text: '운동하기' },
      { done: true, text: '공부하기' },
    ];
  }

해결 방법 3

확실한 할당 주장(definite assignment assertion)인 느낌표('!')를 사용한다. 속성에 느낌표를 붙이면 TypeScript에 속성이 사용되기 전에 값이 할당되도록 할 것임을 알려준다. 다만 이 접근 방식은 초기화 검사를 우회하므로 사용할 때 주의해야 한다. 런타임 오류를 방지하려면 코드의 다른 곳에서 초기화를 적절하게 처리해야 한다. (TypeScript 관련내용 참고)

  name!: string;
  
  todos!: {
    done: boolean,
    text: string;
  }[];

  constructor() {
  }

위 3가지 방법 중 하나를 따르면 앵귤러에서 "Property has no initializer and is not definitely assigned in the constructor" 오류를 해결할 수 있다.