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】関数

Posted at

function

function bmi(height: number, weight: number):number {
  return weight / (height * height)
}

console.log(bmi(1.91, 100))

無名関数

let bmi: (height: number, weight: number) => number = function(height: number, weight: number): number {
  return weight / (height * height)
}

console.log(bmi(1.91, 100))

アロー関数

let bmi: (height: number, weight: number) => number = (
  height: number,
  weight: number
): number =>  weight / (height * height)

console.log(bmi(1.91, 100))

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

// printableはオプショナル
let bmi = (height: number, weight: number, printable?: boolean): number => {
  const bmi: number = weight / (height * height)
  if (printable) {
    console.log({ bmi })
  }
  return bmi
}
// trueはなくても可
bmi(2.4, 92, true)

デフォルトパラメータ

// rateのデフォルト値は1.1
const nextYearSalary = (currentSalary: number, rate: number = 1.1): number => {
  return currentSalary * rate
}

console.log(nextYearSalary(1000))

残余引数

const reducer = (accumulator: number, currentValue: number): 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));

オーバーロード

function double(value: number): number
function double(value: string): string

function double(value: any): any {
  console.log(typeof value)
  if (typeof value === "number") {
    return value * 2 
  } else {
    return value + value
  }
}

console.log(double(200))
// > 400
console.log(double("Foo "))
// > Foo Foo
// console.log(double(true))
// error TS2769: No overload matches this call.
// Overload 1 of 2, '(value: number): number', gave the following error.
//   Argument of type 'boolean' is not assignable to parameter of type 'number'.
// Overload 2 of 2, '(value: string): string', gave the following error.
//   Argument of type 'boolean' is not assignable to parameter of type 'string'.
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?