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】条件値によって戻り値を切り替える型の実装(type-challenges 初級編 268・if)

Last updated at Posted at 2024-12-06

お題

条件値CCがtruthyである場合の戻り値の型TCがfalsyである場合の戻り値の型Fを受け取るIfを実装する。条件値Ctruefalseのどちらかであることが期待されるが、TFは任意の型を取ることができる。

やりたいこと

type A = If<true, "a", "b">; // => "a"
type B = If<false, "a", "b">; // => "b"
type C = If<boolean, "a", "b">; // => "a" | "b"

解答

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

解説

処理の流れ

  • <C extends boolean, T, F>
    Cにはtruefalseが期待されているので、booleanに制限する。
  • C extends true ? T : F
    Conditonal Typesを使って、Cがtruthyなら、T、falsyならFを返す。

なぜbooleanの場合ユニオン型が返されるのか?

type C = If<boolean, "a", "b">; // => "a" | "b"

boolean型はtrue | falseのユニオン型だから。

Conditional Typesとは...

参考記事

今回の問題

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?