Typescript/TypeScript exercises

TypeScript exercises 8번 문제

띵킹 2023. 2. 16. 00:50
interface User {
    type: 'user';
    name: string;
    age: number;
    occupation: string;
}

interface Admin {
    type: 'admin';
    name: string;
    age: number;
    role: string;
}

type PowerUser = unknown;

export type Person = User | Admin | PowerUser;

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' },
    {
        type: 'powerUser',
        name: 'Nikki Stone',
        age: 45,
        role: 'Moderator',
        occupation: 'Cat groomer'
    }
];

function isAdmin(person: Person): person is Admin {
    return person.type === 'admin';
}

function isUser(person: Person): person is User {
    return person.type === 'user';
}

function isPowerUser(person: Person): person is PowerUser {
    return person.type === 'powerUser';
}

export function logPerson(person: Person) {
    let additionalInformation: string = '';
    if (isAdmin(person)) {
        additionalInformation = person.role;
    }
    if (isUser(person)) {
        additionalInformation = person.occupation;
    }
    if (isPowerUser(person)) {
        additionalInformation = `${person.role}, ${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);

console.log();

console.log('Power users:');
persons.filter(isPowerUser).forEach(logPerson);

'type'을 제외한 User와 Admin의 프로퍼티를 모두 가지고 있으면서 powerUser라는 'type'을 가진 타입을 정의하면 된다. 

type PowerUser = Omit<Admin & User ,'type'> & {type: 'powerUser'};

솔루션에는 Omit을 Admin과 User에 각각 걸어줬는데 내 풀이가 더 깔끔하다고 생각한다. 

728x90

'Typescript > TypeScript exercises' 카테고리의 다른 글

TypeScript exercises 9번 문제  (0) 2023.02.16
TypeScript exercises 7번 문제  (0) 2023.02.16
TypeScript exercises 5번 문제  (0) 2023.02.14
TypeScrip texercises 4번 문제  (0) 2023.02.14
TypeScript exercises 3번 문제  (0) 2023.02.14