Skip to content

函数

函数是任何应用的基本构建块,无论它们是本地函数、从另一个模块导入的函数,还是类中的方法。它们也是值,就像其他值一样,TypeScript 有很多方法来描述如何调用函数。让我们学习如何编写描述函数的类型。

函数声明

ts
function isAdult(age: number): boolean {
    return age >= 18
}

// 函数表达式
const grow = function (age: number): number {
    return age + 1;
};

// 箭头函数
const fullName = (firstName: string, lastName: string): string => firstName + lastName

// 函数类型
type MathOperation = (x: number, y: number) => number;
const subtract: MathOperation = (x, y) => x - y;

// 可选参数
function add(x: number, y?: number): number {
    return x + (y || 0);
}

//参数结构
function printPerson({name, age}: { name: string, age: number, sex?: string }) {
    console.log(`姓名: ${name}, 年龄: ${age}, 性别: ${sex || '未知'}`);
}

printPerson({name: '张三', age: 18})

// 剩余参数,放在最后
function printNumbers(oyher: string, ...numbers: number[]) {
}

函数表达式

相当于匿名函数,给定函数模板 描述函数的最简单方法是使用函数类型表达式。这些类型在语法上类似于箭头函数:

ts
function foo(fn: (x: number) => void) {
    foo(666)
}

function print(x: number) {
    console.log(x);
}

foo(print)

函数签名

函数签名描述了函数的参数和返回值类型。

ts
type Fn = {
    str: string;
    (x: number): number;
};

function foo(fn: Fn) {
    console.log(fn.str + fn(6))
}

function getNum(x: number): number {
    return x + 1;
}

getNum.str = "123"
foo(getNum) // 1237

泛型函数

推断

ts
function map<I, O>(arr: I[], fn: (item: I) => O) {
    return arr.map(fn)//js特性:当某函数的参数与传递给高阶函数的参数相同时,可以省略参数类型声明
}

console.log(map([1, 2, 3], item => item + 1));// [2, 3, 4]

TypeScript 可以根据函数表达式 (number) 的返回值推断 Input 类型参数的类型(从给定的 string 数组)以及 Output 类型参数。

约束条件

使用约束条件限制泛型参数的类型 可使用 extends 关键字 如下所示:判断数组中元素长度最长的元素,参数必须是有 length 属性的对象

ts
function judgeMaxLen<T extends { length: number }>(...args: T[]) {
    args.sort((a, b) => a.length - b.length)
    return args[0]
}

console.log(judgeMaxLen('hello', 'world', 'hello world'));
console.log(judgeMaxLen(1, 123, 1234));// 错误:参数必须具有 length 属性

指定参数类型

当指定泛型后,想要传入多个类型数据

ts
function add<T>(x: T, y: T): T {
    return x + y;
}

const result1 = add(1, "a") // 错误:类型不一致
const result2 = add<number, string>(1, "a")
console.log(result);// 1a

函数重载

运行同一个函数根据参数类型返回不同的结果

ts
function add(x: number, y: number): number;
function add(x: string, y: string): string;
function add(x: any, y: any): any {
    return x + y;
}

console.log(add(1, 2));
console.log(add('hello', 'world'));
console.log(add(true, false));

这是我的个人文档