타입 가드: in & instanceof
Coddy JavaScript 여정의 TypeScript 소개 섹션에 포함된 레슨. 73개 중 69번째.
유니온 타입을 작업할 때, 타입 전용 속성이나 메서드에 안전하게 접근하기 전에 현재 어떤 구체적인 타입을 다루고 있는지 확인해야 할 때가 많습니다. 타입 가드는 런타임에 타입을 좁히는 안전한 방법을 제공합니다.
in 연산자는 객체에 특정 속성이 존재하는지 여부를 확인합니다. 이는 서로 다른 속성을 가진 객체 타입들의 유니온(union)을 다룰 때 특히 유용합니다:
type Dog = { name: string; breed: string };
type Cat = { name: string; meow: () => void };
function petSound(pet: Dog | Cat) {
if ('breed' in pet) {
// 여기서 TypeScript는 pet이 Dog라는 것을 압니다
console.log(`${pet.name} is a ${pet.breed}`);
} else {
// 여기서 TypeScript는 pet이 Cat이라는 것을 압니다
pet.meow();
}
}instanceof 연산자는 객체가 특정 생성자 함수나 클래스에 의해 생성되었는지 확인합니다. 아직 클래스를 다루지는 않았지만, 이 연산자는 내장 JavaScript 객체나 사용자 정의 클래스를 작업할 때 유용합니다:
function processValue(value: string | Date) {
if (value instanceof Date) {
// TypeScript는 value가 Date임을 압니다
console.log(value.getFullYear());
} else {
// TypeScript는 value가 string임을 압니다
console.log(value.toUpperCase());
}
}두 연산자 모두 TypeScript 컴파일러가 현재 어떤 타입을 사용 중인지 이해하도록 도와주며, 타입 전용 프로퍼티와 메서드에 안전하게 접근할 수 있게 해줍니다.
챌린지
쉬움in 연산자를 사용하여 서로 다른 유형의 미디어 항목을 처리하는 함수를 만드세요.
두 개의 타입 별칭(type aliases)을 만드세요:
title(string)과director(string) 속성을 가진Movietitle(string)과artist(string) 속성을 가진Song
다음과 같은 기능을 하는 getMediaInfo라는 이름의 함수를 만드세요:
Movie | Song타입의media매개변수를 받습니다.in연산자를 사용하여director속성이 존재하는지 확인합니다.- 영화인 경우
"Movie: [title] directed by [director]"를 반환합니다. - 노래인 경우
"Song: [title] by [artist]"를 반환합니다. - 명시적인 반환 타입으로
string을 가집니다.
다음과 같은 기능을 하는 processValue라는 이름의 두 번째 함수를 만드세요:
string | Date타입의value매개변수를 받습니다.instanceof연산자를 사용하여value가Date인지 확인합니다.Date인 경우 연도를 숫자로 반환합니다 (getFullYear()사용).- 문자열인 경우 문자열 길이를 숫자로 반환합니다.
- 명시적인 반환 타입으로
number를 가집니다.
테스트 데이터를 만드세요:
movie1:{ title: "Inception", director: "Christopher Nolan" }song1:{ title: "Bohemian Rhapsody", artist: "Queen" }movie2:{ title: "The Matrix", director: "The Wachowskis" }song2:{ title: "Imagine", artist: "John Lennon" }testDate:new Date("2023-12-25")testString:"TypeScript"
다음 출력값들을 출력하세요:
movie1을 사용하여getMediaInfo호출song1을 사용하여getMediaInfo호출movie2를 사용하여getMediaInfo호출song2를 사용하여getMediaInfo호출testDate를 사용하여processValue호출testString을 사용하여processValue호출
직접 해보기
// TODO: 여기에 코드를 작성하세요
// Movie와 Song을 위한 타입 별칭 생성
// getMediaInfo 함수 생성
// processValue 함수 생성
// 테스트 데이터 생성
const movie1 = { title: "Inception", director: "Christopher Nolan" };
const song1 = { title: "Bohemian Rhapsody", artist: "Queen" };
const movie2 = { title: "The Matrix", director: "The Wachowskis" };
const song2 = { title: "Imagine", artist: "John Lennon" };
const testDate = new Date("2023-12-25");
const testString = "TypeScript";
// 출력 결과 인쇄
console.log(getMediaInfo(movie1));
console.log(getMediaInfo(song1));
console.log(getMediaInfo(movie2));
console.log(getMediaInfo(song2));
console.log(processValue(testDate));
console.log(processValue(testString));이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
TypeScript 소개의 모든 레슨
직접 연습해 보세요: 온라인 JavaScript 컴파일러