函數(shù)的標(biāo)注
一個函數(shù)的標(biāo)注包含參數(shù)和返回值
// 函數(shù)聲明
function fn(a: string): string {
return a
}
// 函數(shù)表達(dá)式
// 字面量
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
}
可選參數(shù)
// 函數(shù)聲明
function fn(a: string, b?: string): string {
return a
}
fn('1')
fn('1', '2')
// 函數(shù)表達(dá)式
let fn2: (a: string, b?: string) => string = function (a, b) {
return a
}
fn2('1')
fn2('1', '2')
默認(rèn)參數(shù)
有默認(rèn)值的參數(shù)也是可選的
function fn3(a: string, b = ''): string {
return a + b
}
//可以結(jié)合聯(lián)合類型
function fn4(a: string, b: '1' | '2' = '1'): string {
return a + b
}
fn3('1')
fn3('1', '2')
fn4('1', '3')// error
剩余參數(shù)
注意:剩余參數(shù)是一個數(shù)組
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 }
函數(shù)中的this
普通函數(shù)
對于普通函數(shù)而言, this 是會隨著調(diào)用環(huán)境的變化而變化的,所以默認(rèn)情況下,普通函數(shù)中的 this被標(biāo)注為 any .
但可以在函數(shù)的第一個參數(shù)位上顯式的標(biāo)注 this ,(它不占據(jù)實際參數(shù)位置)
interface Iobj {
a: number;
fn: (b: number) => number
}
let obj: Iobj = {
a: 1,
fn(this: Iobj, b) { //標(biāo)注 this,不占據(jù)實際參數(shù)位置
return this.a + b
}
}
console.log(obj.fn(2))//3
let fn2 = obj.fn //但是變成了不是預(yù)期的this類型,ts不會報錯
console.log(fn2(2))//NaN
箭頭函數(shù)
箭頭函數(shù)的this 標(biāo)注類型取決于它所在的作用域 this
interface Iobj {
a: number;
fn: () => Function;
}
let obj: Iobj = {
a: 1,
fn(this: Iobj) {
return () => this
}
}
console.log(obj.fn()());
函數(shù)重載
有時候,同一個函數(shù)會接收不同類型的參數(shù)返回不同類型的返回值,可以使用函數(shù)重載來實現(xiàn)。
重載函數(shù)類型只需要定義結(jié)構(gòu),有一個實現(xiàn)就可以。
//定義結(jié)構(gòu)一
function showOrHide(ele: HTMLElement, attr: 'display', value: 'block' | 'none'): void;
//定義結(jié)構(gòu)二
function showOrHide(ele: HTMLElement, attr: 'opacity', value: number): void;
//實現(xiàn)
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
}