포도가게의 개발일지
TypeScript 본문
반응형
Intersection vs union type
Union type check
interface Bird {
fly(): void;
layEggs(): void;
}
interface Fish {
swim(): void;
layEggs(): void;
}
declare function getSmallPet(): Fish | Bird;
let pet = getSmallPet();
pet.layEggs();
// Only available in one of the two possible types
pet.swim();
Property 'swim' does not exist on type 'Bird | Fish'.
Property 'swim' does not exist on type 'Bird'.
intersection 과 다르게 그냥 해당 집합으로만 정의되어 잘못된 property또는 method가 포함되어 있지 않다.
Intersection
interface ErrorHandling {
success: boolean;
error?: { message: string };
}
interface ArtworksData {
artworks: { title: string }[];
}
interface ArtistsData {
artists: { name: string }[];
}
// These interfaces are composed to have
// consistent error handling, and their own data.
type ArtworksResponse = ArtworksData & ErrorHandling;
type ArtistsResponse = ArtistsData & ErrorHandling;
const handleArtistsResponse = (response: ArtistsResponse) => {
if (response.error) {
console.error(response.error.message);
return;
}
console.log(response.artists);
};
그에 반해 intersection은 합집함으로 정의한다. 때문에 새로 만들어진 집합에 속한 모든 속성에 접근할 수 있게 된다.
Utility type
Record<key type, value type>
const test: Record<string, number> = {
age: 11,
11: 222
};
console.log(test);
// 출력 { '11': 222, age: 11 }
--------------------------------------------------------------------
interface CatInfo {
age: number;
breed: string;
}
type CatName = "miffy" | "boris" | "mordred";
const cats: Record<CatName, CatInfo> = {
miffy: { age: 10, breed: "Persian" },
boris: { age: 5, breed: "Maine Coon" },
mordred: { age: 16, breed: "British Shorthair" },
};
cats.boris;
'[JS,TS,Node]' 카테고리의 다른 글
Prototype chain (0) | 2024.09.22 |
---|---|
[RxJS] RxJS? (0) | 2022.03.26 |
[Js] 고급 문법 (0) | 2022.03.02 |
[Node] 작동 원리 (0) | 2022.02.09 |
[Java Script]생성자 함수, Closure, generator (0) | 2022.02.08 |
Comments