LoginSignup
7
2

More than 3 years have passed since last update.

知識ゼロから始めるTypeScript 〜関数編〜

Last updated at Posted at 2020-03-13

はじめに

基本編の続きです。

TypeScriptシリーズ全4回連載中です:writing_hand:
知識ゼロから始めるTypeScript 〜基本編〜
知識ゼロから始めるTypeScript 〜関数編〜 :point_left:今ココ
知識ゼロから始めるTypeScript 〜クラス編〜
知識ゼロから始めるTypeScript 〜応用編〜

関数の世界でTypeScriptがどう関わっていくのか。
そんな疑問を解決したい。

基本的には引数戻り値この2点に型定義をしていく。

functionキーワードの関数定義

  • 引数returnで返される値に型定義する
function bmi(height: number, weight: number): number {
  // function 関数名(引数名: 引数の型定義): returnで返される型定義
  return weight / (height * height)
}

無名関数の関数定義

  • 関数が格納された変数自体にも型定義する(なんかややこしい)
let bmi: (height: number, weight: number) => number = function(
  height: number,
  weight: number
): number {
  return weight / (height * height)
}

アロー関数による関数定義

  • 少しスッキリ
let bmi: (height: number, weight: number) => number = (
  height: number,
  weight: number
): number => weight / (height * height)
// アロー関数省略記法

オプショナルなパラメータの定義

  • 変数名の末に?を付与する事でオプショナルなパラメータの型定義ができる
  • 下のコードの場合、第三引数に設定されたパラメーターはあってもなくてもエラーにはならない
let bmi: (height: number, weight: number, printable?: boolean) => number = (
  height: number,
  weight: number,
  printable?: boolean
): number => {
  const bmi: number = weight / (height * height)
  if (printable) {
    console.log(bmi)
  }
  return bmi
}

bmi(1.75, 70)

// bmi(身長, 体重, console.logで出力するかどうか?)
// bmi(1.75, 70, true) 出力する
// bmi(1.75, 70, false) 出力しない
// bmi(1.75, 70) 出力しない

デフォルトパラメータの設定

  • 引数の値が未入力の場合のデフォルト値を設定できる。
const nextYearSalary = (currentSalary: number, rate: number = 1.1) => {
  return currentSalary * rate
}

console.log(nextYearSalary(1000))

RESTパラメータの設定

const reducer = (accumulator: number, currentValue: number) => {
  console.log({ accumulator, currentValue })
  return accumulator + currentValue
}

const sum: (...values: number[]) => number = (...values: number[]): number => {
  return values.reduce(reducer)
}

console.log(sum(1, 2, 3, 4, 5))

オーバーロード

  • オーバーロードは関数の実体では型制約を行わない
  • 下記の例ではnumber型string型のみ受け取れる
//関数の前に書く
function double(value: number): number
function double(value: string): string

// 全ての型を受け取れるようにany型で定義
function double(value: any): any {
  if (typeof value === 'number') {
    return value * 2
  } else {
    return value + value
  }
}

console.log(double(100))
console.log(double('GO '))
console.log(double(true)) // コンパイルエラーになる

まとめ

型の基本を抑えていればそこまで難しくなさそう:metal:

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