mosya Type Challenges

問題に挑戦!

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

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

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`
引用元

この問題はType Challengesの以下の問題を記載したものです。

💡ヒント

extendsを使って第一引数のオブジェクトが、typeフィールドに第二引数の型を含むかどうかで条件分岐させると良いでしょう。

🙌 解説はこちら