[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}`);
};