|
| 1 | +// 유니언 타입은 객체가 하나 이상의 |
| 2 | +// 타입이 될 수 있도록 선언하는 방법입니다. |
| 3 | + |
| 4 | +type StringOrNumber = string | number; |
| 5 | +type ProcessStates = "open" | "closed"; |
| 6 | +type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9; |
| 7 | +type AMessyUnion = "hello" | 156 | { error: true }; |
| 8 | + |
| 9 | +// "open"과 "closed"을 문자열과 대비하여 사용하는 것이 새롭게 느껴지신다면, |
| 10 | +// 다음을 확인해보세요: example:literals |
| 11 | + |
| 12 | +// 하나의 유니언에 서로 다른 타입을 혼합할 수 있으며, |
| 13 | +// 여기서 중요한 점은 값은 그 타입 중 하나라는 것입니다. |
| 14 | + |
| 15 | +// TypeScript는 실행 중에 어떤 값이 될 수 있는지 |
| 16 | +// 결정하는 방법을 알아낼 것입니다. |
| 17 | + |
| 18 | +// 예를 들어, 유니언은 가끔 타입을 |
| 19 | +// 여러 개 사용함으로써 기존 의도와 달라질 수 있습니다: |
| 20 | + |
| 21 | +type WindowStates = "open" | "closed" | "minimized" | string; |
| 22 | + |
| 23 | +// 위에를 호버해보면, WindowStates가 유니언 타입이 아닌 |
| 24 | +// string 타입으로 되는 것을 확인할 수 있습니다. |
| 25 | +// 이에 대한 내용은 예시:type-widening-and-narrowing에서 다룹니다. |
| 26 | + |
| 27 | +// 유니언이 OR이면, 교집합은 AND입니다. |
| 28 | +// 교집합 타입은 새로운 타입을 생성하기 위해 두 개의 타입이 교차하는 경우입니다. |
| 29 | +// 이를 통해 타입 구성이 가능합니다. |
| 30 | + |
| 31 | +interface ErrorHandling { |
| 32 | + success: boolean; |
| 33 | + error?: { message: string }; |
| 34 | +} |
| 35 | + |
| 36 | +interface ArtworksData { |
| 37 | + artworks: { title: string }[]; |
| 38 | +} |
| 39 | + |
| 40 | +interface ArtistsData { |
| 41 | + artists: { name: string }[]; |
| 42 | +} |
| 43 | + |
| 44 | +// 이런 인터페이스는 일관된 오류 핸들링과 |
| 45 | +// 자체 데이터 모두를 갖는 응답으로 구성할 수 있습니다. |
| 46 | + |
| 47 | +type ArtworksResponse = ArtworksData & ErrorHandling; |
| 48 | +type ArtistsResponse = ArtistsData & ErrorHandling; |
| 49 | + |
| 50 | +// 예를 들어: |
| 51 | + |
| 52 | +const handleArtistsResponse = (response: ArtistsResponse) => { |
| 53 | + if (response.error) { |
| 54 | + console.error(response.error.message); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + console.log(response.artists); |
| 59 | +}; |
| 60 | + |
| 61 | +// 교집합과 유니언이 혼합된 타입은 |
| 62 | +// 객체가 두 개의 값 중 하나를 포함해야 할 때 |
| 63 | +// 정말 유용합니다: |
| 64 | + |
| 65 | +interface CreateArtistBioBase { |
| 66 | + artistID: string; |
| 67 | + thirdParty?: boolean; |
| 68 | +} |
| 69 | + |
| 70 | +type CreateArtistBioRequest = CreateArtistBioBase & ({ html: string } | { markdown: string }); |
| 71 | + |
| 72 | +// 이제 artistID와 html 또는 markdown 둘 중 하나를 |
| 73 | +// 포함할 때만 요청을 생성할 수 있습니다 |
| 74 | + |
| 75 | +const workingRequest: CreateArtistBioRequest = { |
| 76 | + artistID: "banksy", |
| 77 | + markdown: "Banksy is an anonymous England-based graffiti artist...", |
| 78 | +}; |
| 79 | + |
| 80 | +const badRequest: CreateArtistBioRequest = { |
| 81 | + artistID: "banksy", |
| 82 | +}; |
0 commit comments