TypeScript --函数(一)

90 阅读2分钟

一、完整类型

1、函数类型包含两部分:参数类型和返回值类型

完整类型示例:

let myAdd: (baseValue: number, increment: number) => number =
    function(x: number, y: number): number { return x + y; };

注意不要混淆了 TypeScript 中的 => 和 ES6 中的 =>。 在 TypeScript 的类型定义中,=> 用来表示函数的定义,左边是输入类型,需要用括号括起来,右边是输出类型。

2、按照上下文类型推断,ts会自动正确识别

let myAdd = function(x: number, y: number): number { return x + y; };   

let myAdd: (baseValue: number, increment: number) => number =
    function(x, y) { return x + y; };

二、参数

1、参数要求:传递给一个函数的参数个数必须与函数期望的参数个数一致

2、默认参数:

默认初始化值的参数,当用户没有传递这个参数或传递的值是undefined时,使用默认值

默认参数如果放在末尾,看做可选类型

默认参数出现在必须参数前面,用户必须明确的传入 undefined值来获得默认值

示例如下:

function buildName(firstName: string, lastName = "Smith") {
    return firstName + " " + lastName;
}

let result1 = buildName("Bob");                  // works correctly now, returns "Bob Smith"
let result2 = buildName("Bob", undefined);       // still works, also returns "Bob Smith"
let result3 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters
let result4 = buildName("Bob", "Adams");         // ah, just right



function buildName(firstName = "Will", lastName: string) {
    return firstName + " " + lastName;
}

let result1 = buildName("Bob");                  // error, too few parameters
let result2 = buildName("Bob", "Adams", "Sr.");  // error, too many parameters
let result3 = buildName("Bob", "Adams");         // okay and returns "Bob Adams"
let result4 = buildName(undefined, "Adams");     // okay and returns "Will Adams"

3、剩余参数

表示形式: ...restOfName, restOfName 是一个参数数组名字,可以在函数体内使用

参数个数: 一个或者任意个

参数类型: 可作为可选参数

示例如下:

function buildName(firstName: string, ...restOfName: string[]) {
  return firstName + " " + restOfName.join(" ");
}

4、可选参数

参数可传或不传, 实现方式:参数名旁使用?实现

可选参数必须放在必须参数后面

使用了 --strictNullChecks,可选参数会被自动地加上 | undefined

示例如下:

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



function f(x: number, y?: number) {
    return x + (y || 0);
}
f(1, 2);
f(1);
f(1, undefined);
f(1, null); // error, 'null' is not assignable to 'number | undefined'