[TS] TypeScript Function Type
定義函式的型別
當一個函式被建立但沒有對其參數進行型別註記時,預設會被套用 any
,這是不建議的寫法。
使用 Type Alias 定義函式型別
type Greet = (name: string, age: number) => string;
const greet: Greet = (name, age) => {
return `Hello ${name}, your age is ${age}.`;
};
使用 interface 定義函式的型別
interface Greet {
(name: string, age: number): string;
}
const greet: Greet = (name, age) => {
return `Hello ${name}, your age is ${age}.`;
};
在函式中定義參數的型別
使用箭頭函式
/**
* 範例一
**/
const add = (a: number, b: number): number => a + b;
// 等同於,在變數後直接註記型別為函式
// (a: number, b: number) => number 是 type
const add: (a: number, b: number) => number = (a, b) => a + b;
/**
* 範例二
**/
interface FnParams {
name: string;
phone: string;
}
interface FnResponse {
recipient: string;
body: string;
}
const sendTextMessage = (to: FnParams): FnResponse => ({
recipient: `${to.name} <${to.phone}>`, // Aaron <0912345678>
body: "You're pre-qualified for a loan",
});
使用 function 語法
使用 function
關鍵字來建立函式:
/**
* 範例一
**/
// function statement
function add(x: number, y: number): number {
return x + y;
}
// function expression
const add = function (a: number, b: number): number {
return a + b;
};
/**
* 範例二
**/
interface FnParams {
name: string;
email: string;
}
interface FnResponse {
recipient: string;
body: string;
}
// function statement
function sendEmail(to: FnParams): FnResponse {
return {
recipient: `${to.name} <${to.email}>`, // Aaron <pjchender@gmail.com>
body: "You're pre-qualified for a loan",
};
}
// function expression
const sendEmail = function (to: FnParams): FnResponse {
return {
recipient: `${to.name} <${to.email}>`, // Aaron <pjchender@gmail.com>
body: "You're pre-qualified for a loan",
};
};
參數中解構賦值
const greet = ({ firstName, lastName }: { firstName: string; lastName: string }): void => {
console.log(`Hello ${lastName} ${firstName}`);
};
選填性的參數與參數預設值
Optional and Default Parameters @ TypeScript Docs
選填性參數(optional parameters)
雖然在 JavaScript 中沒有被帶入的函式參數會是 undefined
且可以正常運作,但在 TypeScript 中,函式的參數預設都是必填的,沒填的話 compiler 會直接噴錯。
若有函式的參數需要是選填的,可以在參數後面使用 ?
,例如:
// firstName 是必填,lastName 則可以選填
const getName = (firstName: string, lastName?: string) =>
lastName ? `${firstName} ${lastName}` : firstName;
warning
optional parameter 一定只能放在 required parameter 的後面。