1
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解いてみた 初級 268 easy-if

Last updated at Posted at 2025-04-27

問題


条件値`C``C`が truthy である場合の戻り値の型`T``C`が falsy である場合の戻り値の型`F`を受け取る`If`を実装します。
条件値`C``true``false`のどちらかであることが期待されますが、`T``F` は任意の型をとることができます。

例えば:

```ts
type A = If<true, 'a', 'b'>; // expected to be 'a'
type B = If<false, 'a', 'b'>; // expected to be 'b'
```

回答

type If<C extends boolean, T, F> = C extends true ? T : F;

ちょっと解説

  • C extends boolean,
    C(ジェネリクスの第一引数)がbooleanでない場合エラーを出したいためこう書きます。

  • C extends true ? T : F
    条件付き型 (conditional type)です。
    C(ジェネリクスの第一引数)がtrueである場合Tを、そうでない場合Fを返します。
    今回の場合CC extends booleanと書かれており、booleanであることは確実なのでtrueならT、falseならFを返す形になります。

1
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
1
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?