Typescript-exercises 03

hotbreakb·2022년 6월 13일
0

typescript-exercises

목록 보기
3/12

문제

사용자에게 대한 몇 가지 정보를 추가해 보자.

logPerson() 에러를 고치자. 이 함수는UseroccupationAdminrole의 정보를 출력해야 한다.

코드

export function logPerson(person: Person) {
    let additionalInformation: string;
    if ("role" in person) {
        additionalInformation = person.role;

in

"value" in x
value -> property
x -> union type (object)

object x가 왼쪽에 있는 것을 이름으로 property를 갖고 있는지 확인한다.

type Fish = { swim: () => void };
type Bird = { fly: () => void };
 
function move(animal: Fish | Bird) {
  if ("swim" in animal) {
    return animal.swim();
  }
 
  return animal.fly();
}

🔻 x가 union type이 아니더라도 동작한다.

export type Person = {
    name: string,
    age: number,
    occupation?: string,
    role?: string,
}

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(user: Person) {
    if ("role" in user) {
        console.log(user.name);
    }
}

Union Types: |

유니언 타입을 사용하면 모든 타입에 공통적으로 들어가 있는 속성에만 접근할 수 있다.

// @errors: 2339

interface Bird {
  fly(): void;
  layEggs(): void;
}

interface Fish {
  swim(): void;
  layEggs(): void;
}

declare function getSmallPet(): Fish | Bird;

let pet = getSmallPet();
pet.layEggs();

// Only available in one of the two possible types
pet.swim();

Intersection Types: &

여러 개의 타입을 하나로 묶는다. Union Type과 다르게 공통적인 속성이 아닌 것도 접근할 수 있다.

interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}
 
interface ArtworksData {
  artworks: { title: string }[];
}
 
interface ArtistsData {
  artists: { name: string }[];
}
 
type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;
 
const handleArtistsResponse = (response: ArtistsResponse) => {
  if (response.error) {
    console.error(response.error.message);
    return;
  }
 
  console.log(response.artists);
};

response.error는 아래의 타입이다.

(property) ErrorHandling.error?: {
	message: string;
} | undefined

참고 자료

profile
글쟁이 프론트 개발자, 헬렌입니다.

0개의 댓글