函数重载
函数重载,先要了解什么是函数签名:
函数签名 = 函数名称+函数参数+函数参数类型+返回值类型四者合成,包含了实现签名和重载签名
function funa(value: number, type: string): string
这就是函数签名(重载签名)
type MessageType = "order" | "pay" | string; //微信消息类型
type Message = {
id: number;
type: MessageType;
msg: string;
};
let messages: Message[] = [
{
id: 1,
type: "order",
msg: "订单金额错误",
},
{
id: 2,
type: "pay",
msg: "支付失败",
},
{
id: 3,
type: "order",
msg: "订单无效",
},
{
id: 4,
type: "pay",
msg: "支付回调错误",
},
];
函数重载由一个实现签名 + 一个或多个重载签名合成
function getMessage(value: number): Message; //重载签名1
function getMessage(value: MessageType, count: number): Message[]; //重载签名2
//实现签名↓
//参数类型也可以定义为: any 或 unknown(和any一样都是顶级类型)
function getMessage(value: number | MessageType, count: number = 1) {
//count: number = 1 必须要加这个默认值,因为签名1没有这个参数,函数体中却有,会报错
if (typeof value === "number") {
return messages.find((msg) => {
return value === msg.id;
});
} else {
//过滤后得到多条,在splice确定返回条数
return messages.filter((msg) => value === msg.type).splice(0, count);
}
}
const detail = getMessage(1);
const list = getMessage("pay", 2); //签名定义了必须2个参数
console.log("1:", detail.msg); //这样直接点即可操作,不需要在(<>)转换了
list.forEach((item) => {
console.log("2:", item.msg);
});
构造函数重载
type people = {
name: string;
age: number;
sex?: string;
};
const san: people = {
name: "山姆",
age: 18,
sex: "男",
};
console.log("type类型:", typeof san); //object
class Love {
public name: string;
public age: number;
public sex: string;
constructor(name_: string, age_: number);
constructor(param: people);
//由于构造函数本身不返回任何值,默认this且隐藏,所以重载和实现签名都不返回
constructor(nameOrParam: any, age_: number = 0) {
if (typeof nameOrParam === "object") {
this.name = nameOrParam.name;
this.age = nameOrParam.age;
this.sex = nameOrParam.sex;
} else {
this.name = nameOrParam;
this.age = age_;
this.sex = "未知";
}
}
public show(): string {
let str = `这是一位${this.age}的${this.sex},名叫${this.name}`;
console.log(str);
return str;
}
}
const a = new Love("小丽", 18);
const b = new Love(san);
a.show(); //这是一位18的未知,名叫小丽
b.show(); //这是一位18的男,名叫山姆
export {};
网友评论