12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ReturnTypeを学んだ

Last updated at Posted at 2025-11-30

TypeScript Advent Calendar 1日目の記事です。

業務ではTypeScriptは書いているもののそこまで複雑な実装はしておらず、まだまだTypeScriptの機能を使いこなせているとは言えません。
先日、TSKaigi Hokurikuをオンライン視聴していて、知らない単語ばかり出てきたので、都度調べて得た知見をまとめたく記事にしました。

ReturnTypeとは

関数の戻り値(return の型)を抜き出すためのユーティリティ型です。


const Add = (a: number, b:number) => {
  return a + b;
};
 
type Result = ReturnType<typeof add>; // number

何が嬉しいの?

戻り値が複雑なオブジェクトの関数があるとします。
その関数の型定義を手書きでいちいち書くのは、めっちゃ面倒じゃないですか?
以下のような関数があるとします。


const getInitialUser = () => {
  return {
    id: 12345,
    name: "Guest",
    preferences: {
      theme: "dark",
      notifications: {
        email: true,
        push: false,
        sms: false
      },
      layout: {
        sidebar: "collapsed",
        density: "compact"
      }
    },
    lastLoginAt: new Date(),
    tags: ["new", "trial", "mobile"]
  };
};

この関数の型定義を手書きで書くとこうなります。


type User = {
  id: number;
  name: string;
  preferences: {
    theme: string;
    notifications: {
      email: boolean;
      push: boolean;
      sms: boolean;
    };
    layout: {
      sidebar: string;
      density: string;
    };
  };
  lastLoginAt: Date;
  tags: string[];
};

簡単な戻り値なら良いのですが、複雑な戻り値を手書きで書くとなるとミスをする可能性もあります。
ReturnTypeを使えば、いちいち手書きで書かずとも以下のように1行で型定義ができてしまいます。

type User = ReturnType<typeof getInitialUser>; // 1行で型定義ができちゃう

定義はしたけど中身が分からないのでは?

これだと定義はしたものの、定義元の関数の中身を見ないと何が入っているのかは分からないな、と思われたかもしれません。
もし使っているエディタがVSCodeであれば「Prettify TypeScript」入れると解決すると思います。

参考

12
2
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
12
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?