DAY 9
2
Modern Web

強型闖入DenoLand[8] - TS基礎系列之函式宣告(3)

在函式中應用強型別

``````function sum(para1, para2){
return para1 + para2;
}
let result = sum('Ian',3);
``````

``````function sum(para1: number, para2: number){
return para1 + para2;
}
``````

``````function sum(para1: number, para2: number): number{
return para1 + para2;
}
``````

``````function sum(para1, para2) {
return para1 + para2;
}
``````

``````TS7006 [ERROR]: Parameter 'para1' implicitly has an 'any' type.
function sum(para1, para2)
// ...
``````
``````[ERROR]: Parameter 'para2' implicitly has an 'any' type.
function sum(para1, para2)
// ...
``````

函數表達式

``````function sum(para1: number, para2: number): number{
return para1 + para2;
}
``````

``````let sum = function(para1: number, para2: number): number{
return para1 + para2;
}
``````

``````let sum: (x: number, y: number) => number = function(para1: number, para2: number): number{
return para1 + para2;
}
``````

JavaScript ES6 引入了新的運算子: `...` 來表示展開或其餘運算子。

``````function sum(para1: number, para2: number, para3: number): number{
return para1 + para2 + para3;
}
``````

``````function sumAll(...args) {
let sum = 0;

for (let arg of args) sum += arg;

return sum;
}
sumAll(1,2,3,4,5)
``````

``````function sumAll(para1, para2, ...args) {
let sum = 0;
console.log(para1, para2)
for (let arg of args) sum += arg;

return sum;
}
sumAll(1,2,3,4,5)
``````

``````function sum(para1: number, para2: number): number{
return para1 + para2;
}
let params = [1, 2];
sum(...params)
``````

``````function sum(para1: number, para2: number, para3: number, para4: number): number{
return para1 + para2 + para3 + para4;
}
let params = [1, 2];
sum(5, ...params, 7)
``````

• 在函式定義的輸入使用有 `rest` 的功用。
• 在函式呼叫的輸入使用有 `spread` 的功用。