타입이 여러 개일 때 typeof 등을 사용하여 타입을 하나로 확정 지어 분류하는 것을 의미한다.
const NarrowingFunc = (x :number | string){
if (typeof x === 'number') {
return x + 1
}
else if (typeof x === 'string') {
return x + 1
}
else {
return 0
}
}
Array.isArray(x) 로 narrowing할 수 있다.변수명 as string 형태로 작성하면 타입스크립트 컴파일러가 [변수명] 을 as 뒤에 있는 자료형으로 인지한다. 인지만 하고, 실제로 타입을 바꿔주는 것은 아니다.
const NarrowingFunc = (x :number | string){
return (x as number) + 1
}
console.log( 내함수(123) ) //1231
as 키워드 특징
if (변수 != null)
이렇게 하면 null과 undefined를 동시에 거를 수 있다.
object 자료 narrowing : in
(당연한 얘기이지만) 배타적인 두 object를 in을 사용해서 narrowing할 수 있다.
type Fish = { swim: string };
type Bird = { fly: string };
function findFish(animal: Fish | Bird) {
if ("swim" in animal) {
return animal.swim
}
return animal.fly
}
클래스 Narrowing
new 키워드로 생성된 새로운 object가 있을 때 부모클래스를 검사하기 위해서는 instanceof를 사용하면 된다.
const today = new Date();
if(today instanceof Date) {
console.log(today);
}
서로 비슷한 object
상황 : Car 타입인 경우에는 ‘the car is’, Bike타입인 경우에는 ‘the bike is’라고 콘솔을 찍는다. Car타입과 Bike타입은 완전히 같은 구조의 자료형이다.
type Car = {
wheel : '4개',
color : string
}
type Bike = {
wheel : '2개',
color : string
}
literal type 으로 선언된 속성을 기반으로 narrowing한다. 보통 비슷한 object자료의 경우에는 literal type으로 object안에 각각 유니크한 자료를 달아두면 좋다.
function findCar(x : Car | Bike){
if (x.wheel === '4개'){
console.log('the car is ' + x.color)
} else {
console.log('the bike is ' + x.color)
}
}
else {} 가 없으면 혹은 return하지 않는 조건문이 있으면 버그가 생길 수 있어 에러가 난다. tsconfig.js 에 "noImplicitReturns": false, 를 추가할 수도 있는데, 그냥 엄격하게 사용하는 것이 더 낫다.