LoginSignup
3
2

More than 3 years have passed since last update.

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

Posted at

この記事は何?

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

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

Extract<Type, Union>とは

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

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

Extractは"抜き取る"という意味ですので、Extractは、
Typeの中から、指定したUnion型を抜き取るという意味になります。

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

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

type hogehoge = Extract<Type, 抜き取るUnion型>
// 3つの文字列のうち、"miso", "shoyu"を抜き取る
type Ramen = Extract<"shio" | "shoyu" | "miso", "miso" | "shoyu" > 

// "shio"は抜き取られていないのでアウト
const morning: Ramen = "shio"; // Type '"shio"' is not assignable to type 'Ramen'.
// "shoyu"は抜き取られているのでセーフ
const lunch: Ramen = "shoyu";
// "miso"は抜き取られているのでセーフ
const dinner: Ramen = "miso";

このように、特定の型を抜き取ることが出来ます。
また、関数型も抜き取ることが出来ます。

const jiroRamen = ():string => {
  return "にんにくあぶらからめ"
}

// 3つの型のうち、返り値がstring型の関数を抜き取る
type Ramen = Extract<string | number | (() => string), Function >

// string型が返り値の関数は抜き取られているのでセーフ
const ramen: Ramen = jiroRamen;

// string型は抜き取られていないのでアウト
const morning: Ramen = "文字列"; // Type 'string' is not assignable to type '() => string'.

以上のように、Extractを使えば特定の型を取り除くことが出来ます。

おわりに

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

参考

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