Function Type Expressions),来表示函数类型;
函数类型的定义:(num1: number, num2: number) => void;
-接收两个参数的函数:num1和num2;number类型
-void表示没有返回值;
// type 定义函数的类型
type AddFnType = (num1: number, num2: number) => number
const add: AddFnType = (a1: number, a2: number) => {
return a1 + a2
}
-并且num1和num2在typescript中是不可省略;

可指定某个参数是可选值:
// 可选类型是必须写在必选类型的后面的
// y -> undefined | number
function foo(x: number, y?: number) {
console.log(x, y);
}
参数的默认值
// 必传参数 - 有默认值的参数 - 可选参数
function foo(y: number, x: number = 20) {
console.log(x, y)
}
可推导的this类型
在javascript中有关this的使用,是比较难以理解和把握的知识点;因为this在不同的情况下绑定不痛的值,所有导致对于它的类型难以把握;
我们来翻看一个例子,下面这段代码中会报错;是因为typescript检测到不安全
function sayHell() {
console.log(this.name);
}
const info = {
name: "why",
sayHell: sayHell
};
info.sayHell();
TypeScript会要求我们明确的指定this的类型:
type NameType = {
name: string
}
function sayHell(this: NameType) {
console.log(this.name);
}
type ThisType = { name: string };
function eating(this: ThisType, message: string) {
console.log(this.name + " eating", message);
}
const info = {
name: "why",
eating: eating,
};
// 隐式绑定
info.eating("哈哈哈");
// 显示绑定
eating.call({name: "kobe"}, "呵呵呵")
eating.apply({name: "james"}, ["嘿嘿嘿"])
在TypeScript中,如果我们编写了一个add函数,希望可以对字符串和数字类型进行相加,应该如何编写呢? 我们可能第一反应是想到是使用联合类型去编写;
function add(a1: number | string, a2: number | string) {
return a1 + a2;
}
但是其实是错误的:

在TypeScript中,我们可以去编写不同的重载签名(overload signatures)来表示函数可不同的方式进行
调用;一般编写两个或者以上的重载签名,再去编写一个通用的函数以及实现;
// 函数的重载: 函数的名称相同, 但是参数不同的几个函数, 就是函数的重载
function add(num1: number, num2: number): number; // 没函数体
function add(num1: string, num2: string): string;
function add(num1: any, num2: any): any {
if (typeof num1 === 'string' && typeof num2 === 'string') {
return num1.length + num2.length
}
return num1 + num2
}
当我们定义一个联合类型的函数,有俩种方案可实现:
function getLength(args: string | any[]) {
return args.length
}
console.log(getLength("abc"))
console.log(getLength([123, 321, 123]))
function getLength(args: string): number;
function getLength(args: any[]): number;
function getLength(args: any): number {
return args.length
}
console.log(getLength("abc"))
console.log(getLength([123, 321, 123]))
在可能的情况下,尽量选择使用联合类型来实现;更加的简洁;