๋ฐ์ํ
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.
logPerson ํจ์์ ํ์ ์๋ฌ๋ฅผ ๊ณ ์น์
logPerson ํจ์๋ User์ Admin์ ๋ ๋ค ๋ฐ์์ ์ธํ๊ณผ ์ฐ๊ด๋ ์ ๋ณด๋ฅผ ๋ฐํํด์ผํ๋ค : User๋ผ๋ฉด occupation(์ง์ ), Admin์ด๋ผ๋ฉด role(์ญํ )
Code
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);
Link
https://typescript-exercises.github.io/#exercise=3&file=%2Findex.ts
๋ฐ์ํ
'๐ Type Challenges > Typescript Exercises' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[TS] TypeScript Exercises 5 ํด์ ๋ฐ ํ์ด (0) | 2023.07.17 |
---|---|
[TS] TypeScript Exercises 5 ํด์ ๋ฐ ํ์ด (0) | 2023.07.14 |
[TS] TypeScript Exercises 4 ํด์ ๋ฐ ํ์ด (0) | 2023.07.05 |
[TS] TypeScript Exercises 2 ํด์ ๋ฐ ํ์ด (0) | 2023.07.03 |
[TS] TypeScript Exercises 1 ํด์ ๋ฐ ํ์ด (0) | 2023.07.03 |