函数

相比于javascript,ts增加了对函数参数、返回值的类型校验

function 函数名称 (形参1: 类型, 形参2: 类型) 返回类型 {
  函数体
  retrun 返回值
}

函数的声明

函数的命名

与js一致

函数重载:不支持

因为js不支持,故不支持,下面的代码会报错:

function test(a: string, b: string): string {
    return "hello"
}

function test(a: string): string {
    return "hello"
}

无参函数

function test():void {
}

有参函数

function test(a: number, b number):void {
}

可选参数函数

function buildName(firstName: string, lastName?: string): string {
	if (lastName) {
		return firstName + '' + lastName;
	} else {
		return firstName;
	}
}

无返回值函数

function test(): void {}

无返回值函数:自动推断

function test() {} // 没有return语句,所以推断函数为无返回值函数

有返回值函数

function test(a: number, b number): string { 
  // 如果没有return会报错
  return "hello"; // 这里返回类型推断为 string
}

有返回值函数:返回类型推断

function test(a: number, b number) { 
  // 如果没有return会报错
  return "hello"; // 这里返回类型推断为 string
}

有返回值函数:返回类型可能多种

function test(a: number): string | boolean {
    return "hello"
}

或者使用返回类型推断:

function test(a: number) { // 自动推断返回类型为 : string | boolean
    if (a > 0) {
        return true;
    } else {
        return "haha";
    }
}

永远不返回函数

never代表函数永远不会有返回,比较常见的情况有:

  • 函数内部有while(true) {},函数永远不会走完,比如http服务器

  • 函数不会走完,总是抛出异常,function foo() { throw new Error('Not Implemented') }

这些函数可以定义为never

function foo() { throw new Error('Not Implemented') }

最后更新于