
75
3
장
유니언과 리터럴
값이 할당되기 전에 속성 중 하나에 접근하려는 것처럼 해당 변수를 사용하려고 시도하면 다음
과 같은 오류 메시지가 나타납니다.
let mathematician: string;
mathematician?.length;
//~~~~~~~~~~~//~~~~~~~~~~~
// Error: Variable 'mathematician' is used before being assigned.// Error: Variable 'mathematician' is used before being assigned.
mathematician = "Mark Goldberg";
mathematician.length; // Ok
변수 타입에
undefined
가 포함되어 있는 경우에는 오류가 보고되지 않습니다. 변수 타입에
|
undefined
를 추가하면,
undefined
는 유효한 타입이기 때문에 사용 전에는 정의할 필요가
없음을 타입스크립트에 나타냅니다.
이전 코드 스니펫에서
mathematician
의 타입이
string
|
undefined
이면 어떤 오류도 발생
하지 않습니다.
let mathematician: string | undefined;
mathematician?.length; // Ok
mathematician = "Mark Goldberg";
mathematician.length; ...