Study/TypeScript

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

taecongs 2024. 1. 18. 23:20

 


알고있으면 좋은 Typescript Tip✨


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

  • 위 오류는 2.7.2에부터 도입된 strict class checking으로 인한 오류이다.
    1. TypeScript 2.7에는 strictPropertyInitialization이라는 새로운 플래그가 도입되었다. 이 플래그는 클래스의 각 인스턴스 속성이 생성자 본문 또는 속성 이니셜 라이저에서 초기화되는지 확인하는 검사를 수행한다.
  • tsconfig.json 컴파일러 옵션을 살펴보면 strictPropertyInitialization 옵션이 켜진 상태(true)인걸 볼 수 있다.
    1. 쉽게 말해, 이 옵션이 켜진 환경에선 undefined를 포함하지 않는 클래스 속성이 반드시 속성 선언 또는 생성자, 두 장소 중 한 곳에서 초기화 되어야 한다.
class Employee{
    private _age: number;

    get age(): number{
        return this._age;
    }

    set age(vaule: number){
        if(vaule < 18){
            throw new Error('18세 미만입니다.');
        }
        this._age = vaule;
    }
}

let emp = new Employee();
emp.age = 25;
console.log(emp.age);
  • _age는 속성 선언에서도, 생성자에서도 초기화되지 않고 있으므로 접근되는 시점에 undefined 일 수 있기 때문에 값이 number 타입이 아니므로 타입 에러가 발생한다.

 

(1) 해결 방법 - 플래그 설정

{
    "compilerOptions" : {
    ...
    "strictPropertyInitialization" : false
    }
}
  • tsconfig.json에 compilerOptions에 위의 명령어를 추가한다.

 

(1-2) 해결 방법 - 선택 속성

class Employee{
    private _age?: number;
}
  • 실제 상황을 정확히 반영하기 위해 _age를 선택 속성으로 선언한다.

 

(1-3) 해결 방법 - 확정적 할당 단언 부여

// (1) ! 기호를 붙여 확정적 할당 단언 제공
class Employee{
    private _age!: number;
}

// (2) undefined 작성
class Employee{
    private _age: number | undefined;
}
  • 위와 같이 정의하는 경우 컴파일러는 password의 초기화 체크를 건너뛴다.
  • 즉, 초기화를 하지 않아도 된다.

'Study > TypeScript' 카테고리의 다른 글

[TS] Class  (0) 2023.10.30
[TS] TypeScript 컴파일 과정  (0) 2023.10.30
[TS] 함수 반환 타입 (Function Return Types)  (0) 2023.10.18
[TS] 타입 단언 (Type Assertion)  (0) 2023.10.18
[TS] basic Union Type & Intersection Type  (0) 2023.10.12