定义函数类型
//给函数定义类型的方式
//方式1
function say(hello:string,hi:string):string{
return hello + hi;
}
//方式2
let sayFun:(x:string,y:string)=> string = say;
推断类型
赋值语句的只要有一边写上类型推断后,ts都会自动推断出具体的类型。
let sayFun:(x:string,y:string) => string =function(x,y){
return x + y;
};
let sayFun = function (hello:string,hi:string):string{
return hello + hi;
}
可选参数和默认参数
Typescript要求参数传递的个数跟函数期望的参数个数是一致的,参数名是无所谓的,但是可以使用可选参数和默认参数来预定义参数,不过一定要在必须参数,必须参数之后的默认参数都是可选的。
let sayFun = function (hello:string,name?:string):string{
return hello;
}
剩余参数
剩余参数必须在所有参数之后,剩余参数不限个数,类型一定是数组
function build(firstName: string, ...restOfName: any[]) {
return firstName;
}
this参数
当设置了**--noImplictThis为true**时,当this为any时,会报一个错误。为了返回正确的this类型,我们需要使用箭头函数、或者this参数的形式来确保返回正确的this类型。例如
let deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
createCardPicker: function() {
return function(str) {
//由于this类型自动推断为 any,会抛出错误
return {suit: this.suits[str]};
}
}
}
//箭头函数
let deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
createCardPicker: function() {
//箭头函数this一定指向deck
return (str) => {
return {suit: this.suits[str]};
}
}
}
//this参数,this参数是个假参数,必须在参数列表的第一位,他可以告诉Typescript该函数this期望的是什么类型的对象调用。
interface Deck {
suits: string[];
createCardPicker(this: Deck): () => Card;
}
let deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
createCardPicker: function() {
//这样this就期待自己是deck类型的对象调用了
return function(this:deck){
return {suit: this.suits[str]};
}
}
}
this参数在回调中
这一节详细看文档
重载
javascript是动态语言,函数可以传递不同类型的参数来得到不同的结果,在ts中可以用重载来声明。
function diff(x:string):string;
function diff(x:number):number;
//上面是重载列表,假设脱离重载列表里的两种调用方式,那么就会报错。
function diff(x:string|number):string|number{
return x;
}
为了得到正确的类型,一定要把最精确的放前面,ts的匹配是从上往下检测的,最后一个实体函数,需要把前面参数、返回值所有的情况都全部声明。