최근 마무리한 사이드 프로젝트를 타입스크립트와 리액트를 이용해서 진행했다.
타입스크립트를 공부하던 중 시작하게 된 프로젝트라서 우선 몸으로 부딪혀가며 공부했다.
많은 오류들을 겪었지만 우선 그 중 타입가드에 대해서 작성을 해보려 한다.
타입가드 ?
타입가드
란 객체의 타입을 좁혀서 더욱 안전하고 정확하게 검사를 하는 것을 의미한다.
유니온 타입을(|)을 사용할 때 유용하게 사용할 수 있는 문법이다.
예시를 만들어보며 확인해보자.
원시 타입 (string | number | boolean)
const whatIsType : string = 'frontend';
const typeguardTest = (value : string | number) => {
const changeUp = value.toUpperCase();
console.log(changeUp);
}
typeguardTest(whatIsType);
위 코드를 보면 어디서 잘못 된 것일까 ?
=> typeguardTest의 props로 (string | number)의 타입이 들어오고 whatIsType 이라는 string 타입의 변수를 전달했는데 어째서 안되는 것일까?
이유는 toUppercase() 메서드에 있다. value
는 string 또는 number타입이 들어올텐데, string prototype 메서드를 사용했기 때문이다. 만약 value가 number 타입이라면 오류가 나기 때문에 타입스크립트에서 오류라고 알려주는 것이다.
Property 'toUpperCase' does not exist on type 'string | number'.Property 'toUpperCase' does not exist on type 'number'
정확한 오류의 내용은 위와 같다. 위 오류를 수정하기 위해서는 어떠한 방식을 사용해야 하는지 알아보자.
const typeguardTest = (value : string | number) => {
const changeUp = typeof value === 'string' ? value.toUpperCase() : value.toString();
console.log(changeUp);
}
typeguardTest('frontend');
typeof
를 이용하여 위와 같이 props 의 type이 'string' 일 때만 toUpperCase 메서드를 이용하게 타입가드를 해줄 수 있다.
위의 예제는 삼항연산자를 이용했지만 if
를 이용하여 더욱 깔끔한 코드로도 작성할 수 있을 것이다.
🖥