원티드 타입스크립트 챌린지를 듣고, 추천 받은 공부 방법 중에 exercise를 통해서 1부터 10까지 풀 수 있어야 된다고 해서, exercises를 풀면서 타입스크립트를 학습해보기로 했다.
사이트 : TypeScript Exercises
문제 4 : 에러가 발생한 부분을 수정
interface User {
type: 'user';
name: string;
age: number;
occupation: string;
}
interface Admin {
type: 'admin';
name: string;
age: number;
role: string;
}
export type Person = User | Admin;
export const persons: Person[] = [
{ type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
{ type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
{ type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },
{ type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' }
];
export function isAdmin(person: Person) {
return person.type === 'admin';
}
export function isUser(person: Person) {
return person.type === 'user';
}
export function logPerson(person: Person) {
let additionalInformation: string = '';
if (isAdmin(person)) {
additionalInformation = person.role;
}
if (isUser(person)) {
additionalInformation = person.occupation;
}
console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}
console.log('Admins:');
persons.filter(isAdmin).forEach(logPerson);
console.log();
console.log('Users:');
persons.filter(isUser).forEach(logPerson);
처음에 문제를 풀 때는 조건문의 조건을 단순하게 객체의 속성의 값과 일치하는지 변경하여 문제를 해결해보았다.
interface User {
type: 'user';
name: string;
age: number;
occupation: string;
}
interface Admin {
type: 'admin';
name: string;
age: number;
role: string;
}
export type Person = User | Admin;
export const persons: Person[] = [
{ type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
{ type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
{ type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },
{ type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' }
];
export function isAdmin(person: Person) {
return person.type === 'admin';
}
export function isUser(person: Person) {
return person.type === 'user';
}
export function logPerson(person: Person) {
let additionalInformation: string = '';
if (person.type === 'admin') {
additionalInformation = person.role;
}
if (person.type === 'user') {
additionalInformation = person.occupation;
}
console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}
console.log('Admins:');
persons.filter(isAdmin).forEach(logPerson);
console.log();
console.log('Users:');
persons.filter(isUser).forEach(logPerson);
타입 좁히기를 처리하기 위해 기존에는 Javascript 구조를 사용했지만, 코드에 타입이 어떻게 변하는지 직접 제어하고 싶을 때가 있다.
사용자 정의 타입 가드(user-defined type guard)를 정의하려면, 반환 타입이 type predicate인 함수를 정의해야 된다.
매개변수 is Type
interface Dog {
name: string
bark(): '멍멍'
}
interface Cat {
name: string
meow(): '냐옹'
}
function isDog(animal: Dog | Cat): animal is Dog {
return 'bark' in animal
}
function isCat(animal: Dog | Cat): animal is Cat {
return 'meow' in animal
}
function sayAnimal(animal: Dog | Cat) {
if (isDog(animal)) {
animal.bark()
}
if (isCat(animal)) {
animal.meow()
}
}
interface User {
type: 'user';
name: string;
age: number;
occupation: string;
}
interface Admin {
type: 'admin';
name: string;
age: number;
role: string;
}
export type Person = User | Admin;
export const persons: Person[] = [
{ type: 'user', name: 'Max Mustermann', age: 25, occupation: 'Chimney sweep' },
{ type: 'admin', name: 'Jane Doe', age: 32, role: 'Administrator' },
{ type: 'user', name: 'Kate Müller', age: 23, occupation: 'Astronaut' },
{ type: 'admin', name: 'Bruce Willis', age: 64, role: 'World saver' }
];
export function isAdmin(person: Person): person is Admin {
return person.type === 'admin';
}
export function isUser(person: Person): person is User {
return person.type === 'user';
}
export function logPerson(person: Person) {
let additionalInformation: string = '';
if (isAdmin(person)) {
additionalInformation = person.role;
}
if (isUser(person)) {
additionalInformation = person.occupation;
}
console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}
console.log('Admins:');
persons.filter(isAdmin).forEach(logPerson);
console.log();
console.log('Users:');
persons.filter(isUser).forEach(logPerson);
참고 주소 : https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates