2026.01.01
TS 函数
TypeScript 函数类型定义与重载
函数签名
使用函数类型可以明确定义函数的参数和返回值类型。
type Sum = (a: number, b: number) => number
const sum: Sum = (a, b) => {
return a + b
}
💡 tips:函数签名清晰地表达了「输入什么,输出什么」,让函数的契约一目了然。
函数重载
函数重载允许同一个函数根据不同的参数类型,返回不同类型的值。这在需要处理多种输入场景时非常有用。
使用场景
假设要根据传入的参数类型(string | number)计算一个矩形的面积:
// 重载签名 1:传入 number,返回 number
function calculateArea(length: number, width: number): number
// 重载签名 2:传入 string,返回 string
function calculateArea(length: string, width: string): string
// 实现签名:包含所有可能的情况
function calculateArea(length: number | string, width: number | string): number | string {
if (typeof length === 'number' && typeof width === 'number') {
return length * width
}
if (typeof length === 'string' && typeof width === 'string') {
const lengthNum = Number.parseFloat(length)
const widthNum = Number.parseFloat(width)
if (Number.isNaN(lengthNum) || Number.isNaN(widthNum)) {
throw new TypeError('无效的字符串输入')
}
return (lengthNum * widthNum).toString()
}
throw new Error('参数类型错误')
}
console.log(calculateArea(5, 10)) // 输出: 50
console.log(calculateArea('5', '10')) // 输出: "50"
console.log(calculateArea('5.5', '2')) // 输出: "11"
重载的结构
- 重载签名: 声明函数的不同参数类型和返回值类型
- 实现签名: 实现函数逻辑,处理所有可能的参数组合
// 重载签名 1
function calculateArea(length: number, width: number): number
// 重载签名 2
function calculateArea(length: string, width: string): string
// 实现签名
function calculateArea(length: number | string, width: number | string): number | string {
// 实现逻辑...
}
⚠️ 重载签名与实现必须连续放在一起,中间不能穿插其他内容。