function hello(name:string) {
console.log("Hello " + name + "!")
}
hello("taro")
hello("hanako")
引数に型を指定する
### 変数のスコープ
varは全体で利用可、letは宣言した構文内
– var
function total(max:number){
var num = 0
for(var i = 1; i < max; i++){
num += i
}
console.log("total:" + (num + i))
}
total(100)
total(200)
total(300)
– letにするとエラーになる
let num = 0
for(let i = 1; i < max; i++){
num += i
}
console.log("total:" + (num + i))
Cannot find name ‘i’.
### 戻り値
– 関数の処理実行後に返される値を戻り値という
– 何も戻さない場合はvoidを指定する
function total(max:number):number{
let num = 0
for(let i = 1; i < max; i++){
num += i
}
return num
}
function printTotal(n:number):void {
let res = total(n)
console.log(n + "までの合計:" + res)
}
printTotal(123)
printTotal(1234)
printTotal(12345)
### 複数の値を戻す
タプルを使って複数の値の型を記述する
function calcTax(price:number):[price:number, tax:number]{
const p = price / 1.1
const t = price - p
return [p, t]
}
function printTax(price:number): void {
const [pr, tx] = calcTax(price)
console.log(price + "の本体価格:" + pr + ", 税額:" + tx)
}
printTax(2750)
printTax(3080)
### 引数に条件型
function printPerson(id:number | string, name:string, age:number):void{
switch(typeof(id)){
case 'string':
console.log('your id is "' + id + '".')
break
case 'number':
console.log("No," + id)
break
default:
console.log('wrong id ...')
}
console.log('Name:' + name + '(' + age + ')')
}
printPerson(10, "taro", 39)
printPerson("flower", "hanako", 20)
### オプション引数の関数
オプション引数はnullを許容する
function printPerson(name?:string, age?:number):void{
const nameval = name ? name : "no-name"
const ageval = age ? String(age) : '-'
console.log('Name:' + nameval + '(' + ageval + ')')
}
printPerson("taro", 39)
printPerson("hanako")
printPerson()
– 引数に初期値を入れる方法も一般的
### 可変長引数
const f = (...data:number[]):number => {
let total = 0
for (let i of data){
total += i
}
return total
}
console.log(f(1,2,3,4,5))
console.log(f(10,20,30,40,50,60,70))
console.log(f(123,456,67,89))
なるほど、この数時間でプログラミングの理解がかなり進んだ