函数类型声明
定义函数中各部分的类型。包括函数类型、形参类型、返回值类型、类型、剩余参数
定义变量为函数类型
let test: Function; //函数类型首字母大写
test = () => {};
定义函数形参类型
function test(one: string, two: boolean) {
return one;
}
function test2(one: string, two: boolean, three?: number) {
//使用 ? 进行定义非必填参数,不传时,该属性为undefined
return one;
}
function test3(one: string, two: boolean, three: number = 100) {
//设置形参默认值,不传时,使用默认值
return one;
}
定义函数返回值类型
function test(one: string, two: boolean): string | boolean {
return one;
}
let test2 = (one: string, two: boolean): string | boolean => one;
类型参数声明
type A = { one: string; two: boolean };
let test = (b: A): void => b.one;
指定变量完整函数类型
let test: (a: string, b: number) => void;
test = (x: string, b: number): void => {};
type userType = { name: string; age: number };
type addUserFunc = (user: userType) => boolean;
let addUser: addUserFunc = (u: userType): boolean => {
return true;
};
剩余参数
function test ( one: string , ...args: any[ ] ): void => { } //指定args 数据类型
函数重载
//重载签名
function test(a: string): string;
function test(a: number): number;
//函数实现
function test(a: unknown): unknown {
//正确
return a;
}
function test(a: unknown): string {
//报错,不能将类型“unknown”分配给类型“string”
return a;
}