본문 바로가기

IT

Effective Typescript - 23 - 한꺼번에 객체 생성하기

타입스크립트에서 객체를 표현할 때 한꺼번에 객체의 속성을 명세하는 것이 유리하다.

그 이유는 아래 예제를 참고하면 이해할 수 있다.

const point = {}; //point 의 타입은 {} 이다.
point.x = 5; // 에러 ) x는 속성에 존재하지 않음
point.y = 10; // 에러 ) y는 속성에 존재하지 않음

const pointFix = {
    x: 5,
    y: 10
}
pointFix.x = 10; // 정상
pointFix.y = 15; // 정상



const person = {
    age : 0,
    name : 'jeff'
};

const birth = {
    birth: new Date()
}

const person_with_brithday = {}; // person_with_brithday type은 {}로 추론됨.
Object.assign(person_with_brithday, birth, person);
console.log(person_with_brithday.name); // 에러 'name' 속성이 존재하지 않음.

// 여러 객체를 포함하는 객체 선언시 객체 전개 연산자 '...'를 활용하여 초기화 하는 것을 추천한다.
const person_with_brithday_fix = {
    ...person,
    ...birth
}
//type is
// {
//     birth: Date;
//     age: number;
//     name: string;
// }

console.log(person_with_brithday_fix.name); // 정상

위 예제에서 객체가 여러 객체를 포함하는 유형이라면 객체 전개 연산자 '...' 를 활용하는 것이 타입 추론에 도움이 된다는 사실을 알 수 있다.

 

추가로, 객체 전개 연산자 활용시 조건부를 적용할 수도 있다.

declare let hasMiddle: boolean;
const firstLast = {
    first: 'Harry',
    last: 'Truman'
}

//타입 전개연산자를 활용한 조건부 객체 속성 추가
const president = {
    ...firstLast,
    ...(hasMiddle ? {middle: 'S'} : {})
}
// {
//     middle?: string | undefined;
//     first: string;
//     last: string;
// }