티스토리 뷰

카테고리 없음

Ts intersection vs union type

실전압축코딩 2024. 7. 22. 16:16

intersection 과 union type의 개념이 항상 헷갈리다가 모처럼 정리해보기로 했다.

 

우선 결론 부터 말하자면,

 

intersection ( & ): 두 가지 type전부 만족시켜야 한다. interface extends 키워드와 같은 효과를 지닌다.

union ( | ): 두 가지 type 한가지만 만족시켜도 된다! ( 물론 둘 다 만족시켜도 된다.)

 

type a = {
    a_one: string
    a_two: string
}

type b = {
    b_one: number
    b_two: number
}

// 가능
const _c: a | b = {
    a_one: "_a",
    a_two: "_aa",
}  

// 불가능
const c: a & b = {
    a_one: "_a",
    a_two: "_aa",
}