본문 바로가기

Angular

Angular Property 'paginator' has no initializer and is not definitely assigned in the constructor.ts(2564)

반응형

 

Angular Material MatPaginator 코드 작성 중 에러가 발생했다.

Property 'paginator' has no initializer and is not definitely assigned in the constructor.ts(2564)

 

material 공식 사이트에 있는 matpaginator 예제 그대로 붙여 넣었는데, constructor 에러가 났다.

ts(2564) 에러는 생성자에서 할당해주지 않아 발생하는 오류이다.

 

예제에서는 생성자를 선언하지도 않았고, matpaginator initializer error 키워드로 구글링을 해봐도 명확한 답변을 얻기 어려웠다.

 

 

 

일단 위 에러에 대한 서치 결과

원인 1 : 에러 메시지 그대로 생성자에 할당해주지 않았다.

원인 2 : typescript 버전 문제

 

최신 버전의 angular를 사용하게 되면 '...' has no initializer and is not definitely assigned in the constructor 에러를 마주하게 되는데, 이는 typescript 버전 2.7에 도입된 Strict Class Initialization 플래그 때문이다.

 

has no initializer and is not definitely assigned in the constructor 에러를 검색하다 보면

tsconfig.json 파일에 strictPropertyInitialization 옵션을 false로 설정하면 해결된다는 답변들이 많은데 이것도 해결방안 중 하나이긴 하다.

 

strictPropertyInitialization 옵션은 undefined 일 가능성이 존재한다면 에러를 발생시킨다.

undefined 일 경우 발생할 문제들을 차단하기 위해 체크를 강하게 하는 것이다.

그래서 해당 속성이 true일 경우 속성 선언 또는 생성자에서 반드시 초기화를 시켜줘야 한다.(default : true)

 

 

 

예시 코드

 

해결방안 1 : constructor 에서 초기화

 

 

해결방안 2 : tsconfig.json 파일에 "strictPropertyInitialization" : false 옵션 추가

tsconfig.json

 

 

해결방안 3 : undefined type 추가

 

 

해결방안 4 : 확정 할당 (Definite Assignment Assertions)로 선언

속성 선언 시 느낌표를 붙여 값이 무조건 존재한다는 것을 컴파일러에게 전달해 변수 또는 객체를 사용할 수 있게 한다.

 

 

해결방안 5 : 속성 선언 시 초기화

 

 

 

paginator 해결

  //해결방안 1
  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor(){
    this.paginator = new MatPaginator(new MatPaginatorIntl(), ChangeDetectorRef.prototype);
  }

  //해결방안 3
  paginator: MatPaginator | undefined;

  ngOnInit() {
    if (this.paginator) {
      this.paginator.pageIndex = 0;
    }
  }

  //해결방안 4
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  
  //해결방안 5
  @ViewChild(MatPaginator) paginator: MatPaginator = new MatPaginator(new MatPaginatorIntl(), ChangeDetectorRef.prototype);

구글링을 해보니 속성 선언 시 또는 constructor을 통해 초기화 해주는 방법이 존재하긴 했다.

무난하게 사용할 방법은 undefined type 추가 또는 확정 할당으로 선언해주는 방법인 것 같다.

 

 

 

 

참고:

https://www.angularjswiki.com/angular/property-has-no-initializer-and-is-not-definitely-assigned-in-the-constructor/

 

Property '...' has no initializer and is not definitely assigned in the constructor error fix in Angular | Angular Wiki

There are 5 ways to can fix Property '...' has no initializer and is not definitely assigned in the constructor error in Angular applications

www.angularjswiki.com

https://www.angularjswiki.com/material/mat-table-pagination/

 

Adding pagination to the mat-table using mat-paginator in Angular Material | Angular Wiki

mat-table selector in Angular used to display data in table format

www.angularjswiki.com

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html

 

Documentation - TypeScript 2.7

TypeScript 2.7 Release Notes

www.typescriptlang.org

 

반응형