Back to Type Challenges

README.Ja

questions/00062-medium-type-lookup/README.ja.md

latest2.2 KB
Original Source
<!--info-header-start--><h1>Type Lookup </h1><blockquote><p>by Anthony Fu <a href="https://github.com/antfu" target="_blank">@antfu</a></p></blockquote><p><a href="https://tsch.js.org/62/play/ja" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.md" target="_blank"></a> <a href="./README.zh-CN.md" target="_blank"></a> <a href="./README.ko.md" target="_blank"></a> </p><!--info-header-end-->

Union 型から特定の型を属性を使って取得したいことがあります。

この課題では、Cat | Dog という Union 型に共通する type というフィールドを使って、対応する型を取得します。つまり、以下の例のように、 LookUp<Dog | Cat, 'dog'> の場合は Dog を、LookUp<Dog | Cat, 'cat'> の場合は Cat を取得することになります。

ts
interface Cat {
  type: 'cat'
  breeds: 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal'
}

interface Dog {
  type: 'dog'
  breeds: 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer'
  color: 'brown' | 'white' | 'black'
}

type MyDog = LookUp<Cat | Dog, 'dog'> // expected to be `Dog`
<!--info-footer-start-->

<a href="../../README.ja.md" target="_blank"></a> <a href="https://tsch.js.org/62/answer/ja" target="_blank"></a> <a href="https://tsch.js.org/62/solutions" target="_blank"></a> <!--info-footer-end-->