자바스크립트

Typescript exercise 2 정리

mindun 2024. 9. 26. 16:51
반응형
interface User {
    name: string;
    age: number;
    occupation: string;
}

interface Admin {
    name: string;
    age: number;
    role: string;
}

export type Person = unknown;

export const persons: User[] /* <- 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(user: User) {
    console.log(` - ${user.name}, ${user.age}`);
}

persons.forEach(logPerson);

 

/*

Intro:

    All 2 users liked the idea of the community. We should go
    forward and introduce some order. We are in Germany after all.
    Let's add a couple of admins.

    Initially, we only had users in the in-memory database. After
    introducing Admins, we need to fix the types so that
    everything works well together.

Exercise:

    Type "Person" is missing, please define it and use
    it in persons array and logPerson function in order to fix
    all the TS errors.

*/

 

문제는 대충, 인원이 추가되었는데 추가된 인원의 속성 값이 달라서 인터페이스 하나로 해결이 안되어 에러가 발생했다는 것이다.

 

두 개의 인터페이스 파일이 정의되어있다. 각 인터페이스의 속성 하나가 다르다. 이를 해결하고자 문제에서는

type Person을 생성하고자 한다.

foreach나 logPerson의 어노테이션을 Person으로 바꿔준다. 그러면 이제 Person을 올바르게 정의하는 것만 남았다.

 

나는 Person에 유니온 형식으로 두개의 인터페이스를 작성하여 해결하였다.

 

const type Person: User | Admin; 

반응형