函数的标注
一个函数的标注包含参数和返回值
// 函数声明
function fn(a: string): string {
return a
}
// 函数表达式
// 字面量
let fn2: (a: string) => string = function (a) {
return a
}
// type
type fn = (a: string) => string
let fn3: fn = function (a) {
return a
}
// interface
interface Ifn {
(a: string): string
}
let fn4: Ifn = function (a) {
return a
}
可选参数
// 函数声明
function fn(a: string, b?: string): string {
return a
}
fn('1')
fn('1', '2')
// 函数表达式
let fn2: (a: string, b?: string) => string = function (a, b) {
return a
}
fn2('1')
fn2('1', '2')
默认参数
有默认值的参数也是可选的
function fn3(a: string, b = ''): string {
return a + b
}
//可以结合联合类型
function fn4(a: string, b: '1' | '2' = '1'): string {
return a + b
}
fn3('1')
fn3('1', '2')
fn4('1', '3')// error
剩余参数
注意:剩余参数是一个数组
interface IObj {
[key: string]: any;
}
function merge(target: IObj, ...others: Array<IObj>): IObj {
return Object.assign(target, ...others)
}
let newObj = merge({x: 1}, {y: 2}, {z: 3});
console.log(newObj);//{ x: 1, y: 2, z: 3 }
函数中的this
普通函数
对于普通函数而言, this 是会随着调用环境的变化而变化的,所以默认情况下,普通函数中的 this被标注为 any .
但可以在函数的第一个参数位上显式的标注 this ,(它不占据实际参数位置)
interface Iobj {
a: number;
fn: (b: number) => number
}
let obj: Iobj = {
a: 1,
fn(this: Iobj, b) { //标注 this,不占据实际参数位置
return this.a + b
}
}
console.log(obj.fn(2))//3
let fn2 = obj.fn //但是变成了不是预期的this类型,ts不会报错
console.log(fn2(2))//NaN
箭头函数
箭头函数的this 标注类型取决于它所在的作用域 this
interface Iobj {
a: number;
fn: () => Function;
}
let obj: Iobj = {
a: 1,
fn(this: Iobj) {
return () => this
}
}
console.log(obj.fn()());
函数重载
有时候,同一个函数会接收不同类型的参数返回不同类型的返回值,可以使用函数重载来实现。
重载函数类型只需要定义结构,有一个实现就可以。
//定义结构一
function showOrHide(ele: HTMLElement, attr: 'display', value: 'block' | 'none'): void;
//定义结构二
function showOrHide(ele: HTMLElement, attr: 'opacity', value: number): void;
//实现
function showOrHide(el: HTMLElement, attr: any, value: any) {
if (attr === 'display') {
// ...
} else {
//...
}
}
//使用
let div = document.querySelector('div');
if (div) {
showOrHide(div, 'display', 'block');
showOrHide(div, 'display', 'none');
showOrHide(div, 'opacity', 1);
showOrHide(div, 'opacity', 'block');//error
showOrHide(div, '123', 1);//error
}