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 中級編 2・Get Return Type 解説

Posted at

お題

ReturnType<T>を使用せず、Tの戻り値の型を取得する型MyReturnTypeを実装する。

やりたいこと

type Result1 = MyReturnType<() => string>; // => string

const fn = (v: boolean) => {
  if (v)
    return 1
  else
    return 2
}
  
type Result2 = MyReturnType<typeof fn>; // => "1 | 2"

解答

type MyReturnType<T extends (...args: any[]) => any> = 
  T extends (...args: any[]) => infer U
  ? U
  : never;

解説

処理の流れ

  • <T extends (...args: any[]) => any>
    Tが関数の型であることを制約
  • T extends (...args: any[]) => infer U ? U : never;
    Inferを使って、関数の戻り値の型を推論
    条件分岐に従って、戻り値の型かneverを返す

今回の問題は、初級編 3312・Parametersと似ています。こちらの解説記事を参考にしてみてください!

関数の型を宣言するには?

残余引数とは...

inferとは...

今回の問題

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?