holdanddeepdive / typescript-study

4 stars 0 forks source link

2장(~아이템 12) 타입스크립트의 타입시스템 #18

Open humonnom opened 2 years ago

humonnom commented 2 years ago

타입은 집합이다

interface a {
  name: string;
  age: number;
  password: "a";
}

interface b {
  name: string;
  password: string;
}

// intersection
type c = a & b;
type c_key = keyof (a & b);
type c_key2 = keyof a | keyof b;
// 속성은 합집합이 되고, 타입은 교집합이 된다.
// 구조적 타이핑이 적용되어 아래의 'another'와 같은 별개의 속성이 추가될 수 있다

// 타입 c는 a와 b의 교집합에 위치할 수 있는 타입이어야 함
const obj_c: c = {
  name: "jueun", // string & string
  age: 29, // number
  password: "a", // 'a' & string
  another: "", // 여기서 ts가 내는 오류는 '잉여속성체크'로, 할당이 불가능함을 의미하는 것은 아님 => 엄격한 리터럴 체크
};

const temp_obj_c: c = obj_c;
// 오류 메세지 없이 할당됩니다.
// 임시변수를 도입하면 잉여 속성 체크를 건너뛸 수 있다