0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】Exclude<T, U>の自作(type-challenges 初級編 43・Exclude)

Last updated at Posted at 2024-12-04

お題

Exclude<T, U>を使用せず、ユニオン型TからUで指定したユニオン型を取り除いたユニオン型を返す型MyExcludeを実装する。

やりたいこと

type result = MyExclude<"a" | "b" | "c", "a">  // "b" | "c"

解答

type MyExclude<T, U> = T extends U ? never : T;

解説

処理の流れ

  • <T, U>
    ユニオン型Tと、取り除きたい型Uを引数にとるようにする。
  • Conditional Typesによって評価を行う。
    • Uの場合は、neverを返す
    • Uではない場合は、そのままTの値を返す

そもそもExclude<T,U>とは...

ユニオン型TからUで指定した型を取り除いたユニオン型を返すユーティリティ型

type Grade = "A" | "B" | "C" | "D" | "E";
type PassGrade = Exclude<Grade, "E">; // "A" | "B" | "C" | "D";

ユニオン型の条件分岐の場合に何が起こる?

Conditional TypesのUnion distributionと言う性質により、各要素に対して評価が行われる(分配法則)。

// MyExclude<"a" | "b" | "c", "a"> の場合

("a" extends "a" ? never : "a") | ("b" extends "a" ? never : "b") | ("c" extends "a" ? never : "c")

-> never | "b" | "c"
-> "b" | "c"

Conditional Typesとは...

参考記事

Exclude<T,U>

Exclude | TypeScript入門『サバイバルTypeScript』

Union distribution

ユニオン分配 (union distribution) | TypeScript入門『サバイバルTypeScript』

今回の問題

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?