타입 단언

인터페이스나 객체 타입에 정의되어 있지 않은 속성을 추가하면 에러가 나지 않는다.

화살표 함수

화살표 함수의 경우 타입 선언 자체가 애매해므로, 타입 단언이나 타입 선언을 사용하여 확실하게 타입을 지정해주어야 한다.

const alice: Person = { name : 'Alice' }
const masterYi = { name: 'masterYi' } as Person

const people = ['alice', 'masterYi', 'Teemo'].map(name => ({name}))
// { name: string; }[] 결과가 나오는데, 이를 Person[]로 바꾸고 싶다

/* 타입 단언 사용 */
const people = ['alice', 'masterYi', 'Teemo'].map(
    name => ({name} as Person)
)
// people은 Person[]이 된다. 그러나 이는 런타임에 문제가 발생하게 된다.

const people=['alice','masterYi', 'Teemo'].map(name=>({} as Person));
// 정상적으로 출력이 되므로
console.log(people[0].name) // 런타임에서 오류가 발생한다!!!!!!!!!!!!!!!

이런 경우 타입 선언을 사용하는 것이 좋다.

// 간소화 전
 const people = ['alice', 'masterYi', 'Teemo'].map(name => {
     const person: Person = {name};
     return person
 })

// 간소화 후
const people = ['alice', 'masterYi', 'Teemo'].map(
    (name): Person => ({name})
)

// 혹은
const people: Person[] = ['alice', 'masterYi', 'Teemo'].map(
    (name): Person => ({name})
)

타입 단언을 사용해야 하는 이유