函数
基础定义
显式指定函数参数和返回值的类型
1const add = (a: number, b: number): number => {
2 return a + b;
3}
4/*
5function 函数名(参数:参数类型):返回值的类型{
6 return 返回值
7}
8函数特殊 , 如果一个函数没有return 这个函数返回值类型是 void
9*/
或者用type来声明函数类型
1// (参数:类型)=>返回值类型
2type addFnType = (a: number, b:number) => number;
3let addFn: addFnType = (num1, num2) => {
4 return num1 + num2;
5}
或者用interface来声明函数类型
1//接口指定 函数类型
2interface IFn1{
3 //(参数:类型):返回值类型
4 (name:string):string
5}
6
7let fn1:IFn1 = (name:string)=>{
8 return "我叫"+name
9}
函数参数类型
参数一般有:可选参数、默认参数、剩余参数;
可选参数
在类型标注的:
前添加?
表示 log 函数的参数 x 就是可缺省的;
1function log(msg?: string):void {
2 console.log(msg);
3}
可缺省是不是相当于msg参数的类型就是和string | undefined
等价呢?这个当然不是,string | undefined
的意思是这两个类型中的一种,而可缺省是不传的意思。
默认参数
1function addFn1(num1: number = 1, num2: number = 2):number {
2 return num1 + num2;
3}
函数的默认参数类型必须是参数类型的子类型
1function log3(x: number | string = 'hello') {
2 console.log(x);
3}
这里x参数的类型就是联合类型number | string
,函数默认参数的类型就是联合类型的子类型
剩余参数
1function sum(...nums: number[]) {
2 return nums.reduce((a, b) => a + b, 0);
3}
4sum(1, 2); // => 3
5sum(1, 2, 3); // => 6
this
函数中的this问题,一直都是javascript最令人头疼的问题,因为this的指向只有函数调用的时候才能确定。还有一些可以改变this指向的方法(apply,call,bind)。
但是在Typescript中,必须要明确的指定this的类型(严格模式下)。
1type objType = {person: (n: string) => void, myname: string};
2function person(this: Window | objType , name: string):void {
3 this.myname = name;
4 console.log(this.myname);
5}
6window.person = person;
7window.person('window name');
8let obj:objType = {
9 person,
10 myname: ''
11};
12obj.person('obj name');
单单是上面的代码是有问题的,我们还需要创建一个类型声明文件global.d.ts,为window对象上扩展两个属性person、myname;
1interface Window {
2 person: (n: string) => void;
3 myname: string;
4}
定义对象的函数属性时,只要实际调用中 this 的指向与指定的 this 指向不同,TypeScript 就能发现 this 指向的错误
1interface ObjType2 {
2 name: string;
3 say: (this: ObjType2) => void;
4}
5let obj2:ObjType2 = {
6 name: 'obj2',
7 say() {
8 console.log(this.name);
9 }
10}
11
12obj2.say(); // ok
13
14let t11 = obj2.say;
15t11();
注意
- 显式声明函数的返回值类型为 undfined,则会出现错误提示,如果没有返回值,我们用void表示;
- 注意:显式注解函数中的 this 类型,它表面上占据了第一个形参的位置,但并不意味着函数真的多了一个参数,因为 TypeScript 转译为 JavaScript 后,“伪形参” this 会被抹掉,这算是 TypeScript 为数不多的特有语法。