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'.