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

Posted at

1. ブロック{}を使う場合

const add = (a: number, b: number) => {
    return a + b;
}
  • return が必要。
  • この場合の戻り値は a + b。

2. ブロック{}を省略した場合

const add = (a: number, b:number) => a + b;
  • 1行で書くと、a + b がそのまま戻り値になる。
  • return は不要。

3. オブジェクトを返す時

オブジェクトを返したいときは注意が必要。

// NG: {} が関数ブロックと解釈される
const makeUser = () => { name: "Alice" };

// OK: () で囲めばオブジェクトリテラルだと分かる
const makeUser = () => ({ name: "Alice" });

4. async 関数の場合

const fetchData = async () => {
    const res = await fetch("...");
    return res.json();
};
  • async を付けると、戻り値は必ず Promise になる。
  • 上の例なら戻り値の型は Promise 。
0
0
1

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?