TypeScript 入门 05- 函数类型
05 - 函数类型
定义函数
// 字面量 function add () {} // 箭头函数 const add = () => {}复制代码
显式指定函数参数和返回值的类型
function add (a: number, b: number): number { // ... }复制代码
没有return, 返回undefined, 类型为 void.
使用类似箭头函数的语法表示函数类型的参数和返回值类型
=> 类型仅仅用来定义一个函数类型,而不是实现这个函数。
// 定义函数类型 type Adder = (a: number, b: number) => number // ES6 箭头函数实现 const add: Adder = (a, b) => a + b复制代码
TS 中 => 用来表示函数定义:左侧是参数类型,右侧是返回值类型
ES6 中 => 用来表示函数实现
使用类似对象属性的简写语法,来声明函数类型的属性
interface Entity = { add: (a: number, b: number) => number; del(a: number, b: number): number; } const entity: Entity = { add: (a, b) => a + b, del(a, b) { return a - b } }复制代码
返回值类型
可缺省和可推断的返回值类型
函数返回值的类型推断结合泛型可以实现特别复杂的类型计算。
可以使用 Generator 或 Iterator 的同名接口泛型表示返回值的类型
参数类型
可选参数、默认参数
可缺省参数: x? : string
不可缺省参数: x: string | undefined , 联合类型的参数不可缺省,而且必须是联合类型中的一种
TS会根据默认参数的类型来推断函数参数的类型 : x = 'Hello'
TS也可以显示声明参数的类型: x: string = 'Hello'
函数的默认参数类型必须是参数类型的子类型: x: number | string = 'Hello'
剩余参数
剩余参数类型: ...num: number[] 或 ...num: (number | string ) []
this
通过指定this类型,当我们错误使用了this, TypeScript 就会提示我们
// 只需要在函数的第一个参数中声明this指代的对象 function say (this: Window, name: string) { console.log(this.name) } window.say = say window.say('Hi') // 报错:this实际上应该指向window,但 TS 无法确定say()被谁调用,所以将this的指向默认为 void say('Lily')复制代码
函数重载
函数多态:可以有不同类型的参数和返回值
在 TS 中,可以相应地表达不同类型的参数和返回值的函数
function convert(x: string): number function convert(x: number): string function convert(x: null): -1 function convert(x: string | number | null): any { if (typeof x === 'string') { return Number(x) } if (typeof x === 'number') { return String(x) } return -1 } // 函数重载必须是函数实现的子集,即any 可以找到上面符合的类型复制代码
类型谓词 (is)
在TS中,函数还支持另外一种特殊的类型描述
function isString(s): s is string { // 类型谓词 return typeof s === 'string' } function operator (x: unknown) { if (isString(x)) { // x 类型缩小为 string } }
作者:崔华乐
链接:https://juejin.cn/post/7025889282225078285