Typescript 函数的简单用法

84 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第15天,点击查看活动详情

今天学习的内容是 Typescript 的函数类型。

函数的声明方式

在 JS 中声明函数的常用方式有三种:

1.使用 function关键字声明:

function log(message) {
    console.log(message)
}

2.使用 letconst 关键字声明一个函数表达式:

const log = function (message) {
    console.log(message)
}

3.使用箭头函数:

const add = (a, b) => a + b

在 TS 中声明函数的方法和 JS 中一致,但是需要对参数和返回加上类型限制。比如 add 函数:

使用 function关键字声明:

1.使用 function关键字声明:

function log(message: string):void {
    console.log(message)
}

2.使用 letconst 关键字声明一个函数表达式:

const log = function (message:string):void {
    console.log(message)
}

3.使用箭头函数:

const add = (a: number, b: number) : number => a + b;

let res = add(10, 20);

调用函数时,如果实参类型和形参类型不一致,编译器就会报错

let res = add(10, '20'); // Argument of type 'string' is not assignable to parameter of type 'number'.

意思是 string 类型的实参不能赋值给 number 类型的参数。

并且,函数调用时实参的个数必须和形参保持一致:

let res = add(10); // 报错:An argument for 'b' was not provided.

意思是没有提供参数 b

可选参数

TypeScript 也支持可选参数,需要在定义函数时,将可选的参数使用 ? 表示:

const log = (code: number, message?: string)  => {
    console.log(code, message)
}

log(200, 'Ok'); // 200 Ok
log(404); // 400 undefined

需要注意的是,可选参数的声明,一定要写最后,写在其他必须参数的后面。这样写是错误的:

const log = (code?: number, message: string)  => {
    console.log(code, message)
}

默认参数

TypeScript 函数也支持参数默认值,在定义函数时,在参数类型后使用赋值符号:

const log = (code: number=200, message: string="Ok")  => {
    console.log(code, message)
}

log(); // 200 Ok

函数返回值类型

上面说到了 Typescript 中声明函数时需要定义返回值的类型。其实编译器具有类型推导的能力,即使不写返回值类型,也能从函数体代码中推导出来。

image-20221012095706051

如果一个函数没有返回值,那么它的类型就是 void

小结

本文介绍了 Typescript 的函数类型,和 JS 中使用的区别就是在声明函数签名时需要给参数和返回值确定类型