LoginSignup
3
2

More than 3 years have passed since last update.

【TypeScript】Utility TypesのExcludeを理解する

Last updated at Posted at 2021-03-12

この記事は何?

この記事は、Utility Typesの一つであるExcludeについて理解する記事です。
Utility Typesってそもそも何?という型(方)は以下の記事を御覧ください🙇🏻
👉 TypeScriptのUtility Typesを理解して活用する

そもそも、TypeScriptって何?って型は以下を御覧ください
👉 JavaScriptを知っている方がTypeScriptをなんとなく理解するための記事① ~はじめに~

Exclude<Type, ExcludedUnion>とは

TypeScript公式には以下のように書かれています。

Constructs a type by excluding from Type all union members that are assignable to ExcludedUnion.
ExcludedUnionに割り当て可能なすべてのユニオンメンバーをタイプから除外することにより、タイプを構築します。
https://www.typescriptlang.org/docs/handbook/utility-types.html#excludetype-excludedunion

Excludeは"除く"(除外)という意味ですので、Excludeは、
Typeの中から、ExcludedUnionを除くという意味になります。

つまり、Union型("hoge" | "duga")で記述した型をTypeから除外することが出来ます。

実際にコードの場合、以下のように表すことが出来ます。

type hogehoge = Record<Type, 除くUnion型>
// 3つの文字列のうち、"miso"を除外
type Ramen = Exclude<"shio" | "shoyu" | "miso", "miso" > 

const morning: Ramen = "shio";
const lunch: Ramen = "shoyu";
// "miso"は除外されているので、エラー
const dinner: Ramen = "miso"; // Type '"miso"' is not assignable to type 'Ramen'.

このように、特定の型を取り除くことが出来ます。
同様に複数の型も取り除くことが出来ます。

// 3つの文字列のうち、"miso", "shoyu"を除外
type Ramen = Exclude<"shio" | "shoyu" | "miso", "miso" | "shoyu" > 

const morning: Ramen = "shio";
// "shoyu"は除外されているのでエラー
const lunch: Ramen = "shoyu"; // Type '"shoyu"' is not assignable to type '"shio"'.
// "miso"は除外されているので、エラー
const dinner: Ramen = "miso"; // Type '"miso"' is not assignable to type 'Ramen'.

以上のように、Excludeを使えば特定の型を除外することが出来ます。

おわりに

今回は、Utility TypesのExcludeについて紹介しました。
是非、ご活用ください!

参考

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2