DAY 9
1

## 【Day 09】TypeScript 資料型別 - 函式型別(Function Types)-(下)

• 函式在 TypeScript 的型別推論和型別註記機制為何？
• 若參數推論為 any 型別，TS 會如何進行編譯呢？

## 函式沒有回傳值：void

``````function add(x: number, y: number) {
console.log(x + y)
}
``````

``````//1. 函式沒有回傳值 => 回傳值推論為void，PASS!
function add(x: number, y: number) {
console.log(x + y)
}

//2. 函式回傳undefined => 回傳值推論為undefined，PASS!
function add1(x: number, y: number) {
return undefined
}

//3. 函式回傳值註記型別為 undefined，回傳 undefined => 回傳值型別為undefined，PASS!
function add2(x: number, y: number):undefined {
return undefined
}

//4. 函式回傳值註記型別為 undefined，但函式沒有回傳值 => 報錯
function add3(x: number, y: number):undefined {
console.log(x+y)
}

//5. 函式回傳值註記型別為 undefined，但函式內容為空 => 報錯
function add3(x: number, y: number):undefined {

}

//6. 函式回傳值註記為 void，但函式回傳 undefined => PASS!
function add4(x: number, y: number):void {
return undefined
}

//7. 函式回傳值註記為 void，但函式沒有回傳值 => PASS!
function add5(x: number, y: number):void {
console.log(x + y)
}
``````

## 函式可選參數和預設參數

``````function foo(bar: number, bas?: string): void {
console.log(bar, bas)
}

foo(123); //(123, undefined)
foo(123, 'hello'); //(123, "hello")
foo(123, 'hello','world') // Error : Expected 1-2 arguments, but got 3
foo() // Error: Expected 1-2 arguments, but got 0
``````

``````function foo(bar: number, bas: string = 'hello') {
console.log(bar, bas);
}

foo(123);           // 123 "hello"
foo(123, 'world');  // 123 "world"
``````

``````//可選參數後面不允許必要參數，報錯
function foo(bar?: number, bas: string): void {
console.log(bar, bas)
}
//Error: A required parameter cannot follow an optional parameter.
``````

## 剩餘參數(rest parameters)

``````function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}

let a = buildName("Joseph", "Samuel", "Lucas", "MacKinzie")
console.log(a) //Joseph Samuel Lucas MacKinzie

``````

TS 允許我們定義一個函式接受不同數量或類型的參數，編譯器會根據其型別定義處理函式的調用，例如：我們需要有一個函式 add，輸入數字 1 和 2 時，回傳相加總和3，而輸入字串'hello'和'Kira'時，回傳相連字串'hello Kira'。

``````function add(a:string, b:string):string;
function add(a: any, b:any): any {
return a + b;
}

add("hello ", "Kira"); // "hello Kira"
``````

## 小結

Typescript 初心者手札30