const metrics = 'cm' | 'inch';
const quantity = 50 | 100;
타입의 값을 명시적으로 지정하여 특정 값만 할당할 수 있도록 제한을 둘 수 있는 타입 방식이다.
type Quantity = 50 | 100;
let quantity: Quantity = 51 // error
let quantity2: Quantity = 50
let quantity3: Quantity = 100
type Metrics = 'cm' | 'inch';
const metrics: Metrics = 'cm';
type alias
를 이용하여 여러 다른 변수에 똑같은 타입 지정을 하면 생산성이 증대된다.
function greet(name: string) {
console.log(name);
}
greet(null) // error
greet
함수의 인자에 타입 string
이 지정되어 있으므로 null
값을 패스하는건 `Argument of type null is not assignable to parameter of type string 에러를 발생시킨다.
//tsconfig.json
"strict": true,
// "strictNullChecks": true
tsconfig.json
파일을 보면 strictNullChecks
옵션이 비활성화되어 있고 strict
옵션이 true
가 되어있는 것을 볼 수 있는데 strict
옵션이 활성화되어있다면 strictNullChecks
기능도 포함하여 활성화된 상태다. "strictNullChecks": false
로 지정해주면 strict: true
여도 null
타입에 대한 엄격한 타입 체크가 해제되고 다음과 같은 상황이 발생하는게 가능해진다.
function greet(name: string) {
console.log(name);
}
greet(null); // 정상 작동
위와 같은 상황을 예방하기 위하여 structNullChecks: false
옵션은 조심하는 것이 좋다. 그렇다면, 프로그램 내에서 특정 코드만 예외적으로 null
값을 패스해도 되는 상황이 필요할 땐 유니온 타입 지정으로 해결할 수 있다.
function greet(name: string | null) {
console.log(name);
}
greet(null); // 정상 작동
type Customer = {
birthday: Date
}
function getCustomer(id: number): Customer | null | undefined {
return id === 0: null ? { birthday: new Date() }
}
let customer = getCustomer(0);
console.log(customer.birthday); // 에러
위 코드의 문제는 id
값이 0
이 되었기 때문에 getCustomer()
함수는 null
을 리턴하였고 customer
에는 null
이 할당된 상황이다.
그러므로 .birthday
프로퍼티를 사용할 수 없다.
Object is possibly null
에러가 터지고 프로그램이 충돌할 것이다.
이를 방지하기 위한 방법으로
let customer = getCustomer(0);
if (customer !== null && customer !== undefined )
console.log(customer.birthday);
if
문을 두는 type narrowing
으로 에러를 방지할 수 있다.
하지만 더 간단하게 하는 방법이 있다.
customer?.birthday;
?
optional chaining
을 사용한다면 customer
가 null
값일때 .birthday
를 읽지않고 넘어가 에러를 방지할 수 있다.