- • 参数类型和返回值类型需要显式定义
- • 使用 type 定义函数类型表达式
- • 回调函数使用类型别名更清晰
- • void 表示无返回值的函数
4.1 函数类型定义
为函数添加类型约束
🎯 学习目标
- 掌握函数参数和返回值的类型定义
- 理解函数类型表达式的写法
- 学会使用类型别名定义函数类型
- 了解函数重载的基本概念
📝 基本语法
// 函数声明:参数和返回值类型
function add(a: number, b: number): number {
return a + b;
}
// 函数表达式
const subtract = function(a: number, b: number): number {
return a - b;
};
// 箭头函数
const multiply = (a: number, b: number): number => a * b;
// 无返回值
function log(message: string): void {
console.log(message);
}
🔧 函数类型表达式
// 定义函数类型
type MathOperation = (a: number, b: number) => number;
// 使用函数类型
const add: MathOperation = (a, b) => a + b;
const subtract: MathOperation = (a, b) => a - b;
// 作为参数类型
function calculate(op: MathOperation, a: number, b: number): number {
return op(a, b);
}
// 作为对象属性类型
interface Calculator {
add: MathOperation;
subtract: MathOperation;
}
💻 实际应用
// 回调函数类型
type Callback = (error: Error | null, data?: string) => void;
function fetchData(url: string, callback: Callback): void {
// 模拟异步操作
setTimeout(() => {
callback(null, 'data');
}, 1000);
}
// 事件处理类型
type EventHandler = (event: Event) => void;
function addListener(element: HTMLElement, event: string, handler: EventHandler) {
element.addEventListener(event, handler);
}
// 工厂函数类型
type Factory<T> = () => T;
function createInstance<T>(factory: Factory<T>): T {
return factory();
}
📝 本节小结
✅