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?

type-challenges解いてみた 初級 43 - Exclude編

Last updated at Posted at 2025-03-16

問題


組み込みの型ユーティリティ`Exclude <T, U>`を使用せず、`U`に割り当て可能な型を`T`から除外する型を実装します。

例えば:

```ts
type Result = MyExclude<'a' | 'b' | 'c', 'a'> // 'b' | 'c'
```

回答

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

ちょっと解説

  • 条件型
    T extends U ? X : Yという形式で書かれ、TU に割り当て可能であれば X を、そうでなければ Y を返します。

  • type MyExclude<T, U> = T extends U ? never : T;
    この場合では、T の各要素が U に割り当て可能かどうかをチェックしています。
    T の要素が U に割り当て可能なら、その要素は never に置き換えられます。
    never はユニオン型から除外されるため、結果 U に割り当て可能な部分が取り除かれるというわけです。

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?