๐Ÿ’™ Type Challenges/Typescript Exercises

[TS] TypeScript Exercises 3 ํ•ด์„ ๋ฐ ํ’€์ด

์„ ๋‹ฌ 2023. 7. 4. 20:46
๋ฐ˜์‘ํ˜•

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

 

TypeScript Exercises

A set of interactive TypeScript exercises

typescript-exercises.github.io

 

๋ฐ˜์‘ํ˜•