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?

More than 1 year has passed since last update.

typescript function文とfunction式

Last updated at Posted at 2023-02-28

今まで雰囲気で書いてましたが、ある本を読んでなるほどと思ったのでメモです。
型定義を共通して使えるという理由でfunction式(アロー関数)の使用を推奨されてました。
(他にも違いはあると思いますが……)

function文の場合

function文の場合、全ての関数定義に型付けする必要があり煩雑ですよね。
さらに、引数や戻り値が変わった場合すべてを修正する必要があります。

function add(a: number, b: number): number {
  return a + b;
}

function subtract(a: number, b: number): number {
  return a - b;
}

function multiply(a: number, b: number): number {
  return a * b;
}

function divide(a: number, b: number): number {
  return a / b;
}

function式の場合

下記のように型定義をCalcTypeでまとめることができ、変更があった場合も一か所の修正で済むようにできました。
(まあ、型が変われば関数の実装も変わるんだろうけど。。。)

type CalcType = (a: number, b: number) => number;

const add: CalcType = (a, b) => a + b;
const subtract: CalcType = (a, b) => a - b;
const multiply: CalcType = (a, b) => a * b;
const divide: CalcType = (a, b) => a / b;

参考になれば幸いです。

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?