TypeScript:完整的函数类型书写方式
在TypeScript中,函数类型用于定义函数的签名,包括参数类型、返回值类型以及可选特性(如可选参数、默认参数、剩余参数)。
1. 函数类型表达式
这是最直接的方式,使用箭头语法定义函数类型。语法为:(参数1: 类型1, 参数2: 类型2, ...) => 返回值类型
。适用于变量或参数的类型注解。
// 定义一个函数类型变量
let add: (a: number, b: number) => number;
add = (x, y) => x + y; // 实现必须匹配类型// 作为参数传递
function calculate(operation: (x: number, y: number) => number, a: number, b: number): number {return operation(a, b);
}
console.log(calculate(add, 2, 3)); // 输出 5
2. 接口定义函数类型
通过接口(interface)定义函数类型,特别适合需要复用或添加额外属性的场景。语法为:interface 接口名 { (参数: 类型): 返回值类型; }
。
// 定义一个函数接口
interface MathOperation {(a: number, b: number): number;
}// 实现接口
let multiply: MathOperation = (x, y) => x * y;// 接口可扩展属性(如函数描述)
interface AdvancedOperation extends MathOperation {description: string;
}
let customOp: AdvancedOperation = (x, y) => x - y;
customOp.description = "减法操作";
3. 类型别名(Type Alias)
使用 type
关键字定义函数类型别名,语法类似函数类型表达式:type 类型名 = (参数: 类型) => 返回值类型;
。适合简化复杂类型。
// 定义类型别名
type StringConverter = (input: string) => string;// 使用类型别名
let toUpperCase: StringConverter = (str) => str.toUpperCase();
console.log(toUpperCase("hello")); // 输出 "HELLO"
4. 可选参数、默认参数和剩余参数
可选参数:使用
?
标记,如(param?: type)
。默认参数:在函数实现中指定默认值,但类型定义需包含可选性。
剩余参数:使用
...rest: type[]
表示可变参数列表。
// 函数类型包含可选和剩余参数
type Logger = (message: string, prefix?: string, ...details: any[]) => void;// 实现
const log: Logger = (msg, prefix = "Info", ...args) => {console.log(`${prefix}: ${msg}`, args);
};
log("Error occurred", "Alert", "code: 500", "time: now"); // 输出 "Alert: Error occurred" 和剩余参数
5. 函数重载(Overloads)
TypeScript 支持函数重载,通过多个签名定义不同参数组合,最后用实现签名统一处理。语法为:先声明多个重载签名,然后一个兼容的实现签名。
// 重载示例:处理不同输入类型
function combine(input: string, times: number): string;
function combine(input: number, times: number): number;
function combine(input: any, times: number): any {if (typeof input === "string") {return input.repeat(times);} else if (typeof input === "number") {return input * times;}
}
console.log(combine("Hi", 3)); // 输出 "HiHiHi"
console.log(combine(5, 3)); // 输出 15
关键点总结
函数类型确保类型安全,防止参数或返回值类型错误。
优先使用函数类型表达式或类型别名简化代码;接口适合需要扩展属性的场景。
可选参数和剩余参数增强灵活性,但需注意实现时的默认值处理。
重载用于处理多态行为,但实现签名需兼容所有重载。