![[Typescript] 객체(2)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FsdasD%2FbtsEEXjK4Av%2FU2WqhlV8RKG4dNLsY3GKY0%2Fimg.png)

3️⃣객체 타입 유니언
유니언 : 값에 허용된 타입을 두 개 이상으로 확장하는 것
🚩유추된 객체 타입 유니언
변수에 여러 객체 타입 중 하나가 될 수 있는 초기값이 주어지면 Typescript는 해당 타입을 객체 타입 유니언으로 유추한다.
유니언 타입은 가능한 각 객체 타입을 구성하고 있는 요소를 모두 가질 수 있다.
const poem = Math.random() > 0.5 ? { name:"The Double Image", pages:7}:{ name:"Her Kind",rhymes:true};console.log(typeof(poem.name)); /*string*/console.log(typeof(poem.pages)); /*number | undefined*/console.log(typeof(poem.rhymes)); /*boolean | undefined*/

🚩명시된 객체 타입 유니언
객체 타입의 조합을 명시하면 객체 타입을 더 명확히 정의할 수 있다.
값의 타입이 "객체 타입으로 구성된 유니언"이라면 타입시스템은 이런 모든 유니언 타입에 존재하는 속성에 대한 접근만 허용한다.
type BookWithPages = { name : string; pages: number; };type BookWithDate = { name : string; date : boolean;}type Book = BookWithPages | BookWithDate;const book : Book = Math.random() > 0.5 ? { name : "React for typescript" , pages : 345} : { name: "React for Javascript", date : true};book.name; /*OK*/book.pages; /*Error*/book.date; /*Error*/

🚩객체 타입 내로잉
if("pages" in book){ book.pages; /*OK : book이 BookWithPages로 좁혀짐*/}else{ book.date; /*OK : book이 BookWithDate로 좁혀짐*/}
이렇게 Typescript의 타입검사기가 유니언 타입 값에 특정 속성을 포함한 경우에만 해당 코드 영역을 실행할 수 있다는 것을 알게 되면,
값의 타입을 해당 속성을 포함하는 구성 요소로만 좁힌다.
⭐️타입가드의 역할을 하는 것임을 알 수 있고 타입 내로잉 없이는 값에 존재하는 속성을 보장할 수 없다.
🚨Typescript는 if ( book.pages ) 와 같은 코드로 참 여부를 확인하는 것을 허용하지 않는다.
왜냐하면 존재하지 않는 객체의 속성에 접근하려고 하면 타입가드처럼 작동하더라도 타입 검사기가 타입 에러로 간주하기 때문.
🚩판별된 유니언
유니언 타입으로 된 객체의 형태 중 멋진 형태는 "객체의 속성이 객체의 형태를 나타내도록 하는 것"이다.
객체의 속성이 객체의 형태를 나타내도록 하는 방법은 아래와 같다.
type FlowerWithBugs = { name : string; bugs : boolean; type : 'bugs';};type FlowerWithCount = { name : string; count : number; type : 'count'};type Flower = FlowerWithBugs | FlowerWithCount;const flower : Flower = Math.random() > 0.5 ? { name: "Sunflower", bugs : true, type: "bugs"}: { name : "Rose", count: 3, type: "count"};if (flower.type === "bugs"){ console.log(`거기 벌레가 있나?\n${flower.bugs}`);}else { console.log(`몇개 있는데?${flower.count}`);}flower.type;flower.bugs; /*Error : 내로잉이 될때만 접근가능*/flower.count; /*Error : 내로잉이 될때만 접근가능*/

4️⃣교차 타입
두 객체의 타입을 합집합의 형태로도 만들 수 있다.
교차타입(&)을 사용해 여러 타입을 동시에 나타낼 수 있다.
type ObjectType1 = { name : string; age : number; sex : boolean;}type ObjectType2 = { name : string; phone : number; date : Date;};type IntersectionType = ObjectType1 & ObjectType2;// IntersectionType이 가지는 결과// {// name : string;// age : number;// sex : boolean;// phone : number;// date : Date;// }
Q : 만약 이름이 같은 속성에 다른 타입이 주어지면 어떻게 될까?
A : never 타입이 된다.
never 키워드와 never 타입은 프로그래밍 언어에서 "empty타입" 또는 "bottom타입"을 뜻한다.
두 타입은 값을 가질 수 없고 참조할 수 없는 타입이므로 이 두 타입에 어떠한 타입도 제공할 수 없다.
'FrontEnd > Typescript' 카테고리의 다른 글
[Typescript] 함수(2) (0) | 2024.03.06 |
---|---|
[Typescript] 함수(1) (1) | 2024.03.05 |
[Typescript] 객체(1) (1) | 2024.02.09 |
[Typescript] 유니언과 리터럴(2) (1) | 2023.12.27 |
[Typescript] 유니언과 리터럴(1) (0) | 2023.11.20 |
안녕하세요? 개발자입니다.