Ex 3
๋ฌธ์
/*
Intro:
Since we already have some of the additional
information about our users, it's a good idea
to output it in a nice way.
Exercise:
Fix type errors in logPerson function.
logPerson function should accept both User and Admin
and should output relevant information according to
the input: occupation for User and role for Admin.
*/
interface User {
name: string;
age: number;
occupation: string;
}
interface Admin {
name: string;
age: number;
role: string;
}
export type Person = User | Admin;
export const persons: Person[] = [
{
name: 'Max Mustermann',
age: 25,
occupation: 'Chimney sweep'
},
{
name: 'Jane Doe',
age: 32,
role: 'Administrator'
},
{
name: 'Kate Mรผller',
age: 23,
occupation: 'Astronaut'
},
{
name: 'Bruce Willis',
age: 64,
role: 'World saver'
}
];
export function logPerson(person: Person) {
let additionalInformation: string;
if (person.role) {
additionalInformation = person.role;
} else {
additionalInformation = person.occupation;
}
console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}
persons.forEach(logPerson);
// In case you are stuck:
// https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing
ํ์ด
narrowing ๊ด๋ จ ๋ฌธ์ , ํ์ Person์ ํด๋นํ๋ User, Admin ๋ interface ์ค ํ๋์ ์กฐ๊ฑด์ ์ถฉ์กฑํ ๋ ์ด๋ป๊ฒ ํ ๊ฑฐ๋๋ ๋ฌธ์ ์ด๋ค.
User์ Admin์ occupation ๊ณผ role ์ด ๋ค๋ฅด๋ค. ๊ทธ ์ฐจ์ด๋ฅผ ์ด์ฉํด ํ์ ์ narrowing ํ๋ค.
interface User {
name: string;
age: number;
occupation: string;
}
interface Admin {
name: string;
age: number;
role: string;
}
export type Person = User | Admin;
export const persons: Person[] = [
{
name: 'Max Mustermann',
age: 25,
occupation: 'Chimney sweep'
},
{
name: 'Jane Doe',
age: 32,
role: 'Administrator'
},
{
name: 'Kate Mรผller',
age: 23,
occupation: 'Astronaut'
},
{
name: 'Bruce Willis',
age: 64,
role: 'World saver'
}
];
export function logPerson(person: Person) {
let additionalInformation: string;
if ("role" in person) {
additionalInformation = person.role;
} else {
additionalInformation = person.occupation;
}
console.log(` - ${person.name}, ${person.age}, ${additionalInformation}`);
}
persons.forEach(logPerson);Last updated
Was this helpful?