返回值类型
需要注意的是,在 TypeScript 中,如果我们显式声明函数的返回值类型为 undfined,将会得到如下所示的错误提醒。
function fn(): undefined { // ts(2355) A function whose declared type is neither 'void' nor 'any' must return a value// TODO}
需要注意的是,这里的=>与 ES6 中箭头函数的=>有所不同。TypeScript 函数类型中的=>用来表示函数的定义,其左侧是函数的参数类型,右侧是函数的返回值类型;而 ES6 中的=>是函数的实现。
参数类型
1. 可选参数
?: 表示参数可以缺省、可以不传,也就是说调用函数时,我们可以不显式传入参数。但是,如果我们声明了参数类型为 xxx | undefined,就表示函数参数是不可缺省且类型必须是 xxx 或者 undfined。
2. 默认参数
在 ES6 中支持函数默认参数的功能,而 TypeScript 会根据函数的默认参数的类型来推断函数参数的类型
function log(x = 'hello') {console.log(x);}log(); // => 'hello'log('hi'); // => 'hi'log(1); // ts(2345) Argument of type '1' is not assignable to parameter of type 'string | undefined
在上述示例中,根据函数的默认参数 ‘hello’ ,TypeScript 推断出了 x 的类型为 string | undefined。
3. 剩余参数
没撒可记录的。
TS 中如何声明 this 类型
解决方案:我们只需要在函数的第一个参数中声明 this 指代的对象(即函数被调用的方式)即可。
function say(this: Window, name: string) {console.log(this.name);}window.say = say;window.say('hi');
需要注意的是,如果我们直接调用 say(),this 实际上应该指向全局变量 window,但是因为 TypeScript 无法确定 say 函数被谁调用,所以将 this 的指向默认为 void,也就提示了一个 ts(2684) 错误。
注意:显式注解函数中的 this 类型,它表面上占据了第一个形参的位置,但并不意味着函数真的多了一个参数,因为 TypeScript 转译为 JavaScript 后,“伪形参” this 会被抹掉,这算是 TypeScript 为数不多的特有语法。
函数重载
function convert(x: string): number;function convert(x: number): string;function convert(x: null): -1;function convert(x: string | number | null): any {if (typeof x === 'string') {return Number(x);}if (typeof x === 'number') {return String(x);}return -1;}const x1 = convert('1'); // => numberconst x2 = convert(1); // => stringconst x3 = convert(null); // -1
注意:函数重载列表的各个成员(即示例中的 1 ~ 3 行)必须是函数实现(即示例中的第 4 行)的子集,例如 “function convert(x: string): number”是“function convert(x: string | number | null): any”的子集。
类型谓词(is)
function isString(s): s is string {return typeof s === 'string';}window.isString = isString;window.isString();
