TS整合之函数重载
函数重载是有一个函数实现签名外加一个或者多个函数重载签名组成
一组具有相同名字,不同参数列表和返回值无关的函数
函数签名即指:函数名 函数参数 参数类型 返回值类型四者合成
interface Message { id: number type: string sendmessage: string } type MessageType = 'image' | 'audio' | string const messages: Message[] = [ { id: 1, type: 'audio', sendmessage: '你好啊,今晚咱们一起去三里屯吧' }, { id: 2, type: 'audio', sendmessage: '朝辞白帝彩云间,千里江陵一日还' }, { id: 3, type: 'audio', sendmessage: '你好!张无忌' }, { id: 4, type: 'audio', sendmessage: '刘老根苦练舞台绝技!' }, { id: 5, type: 'audio', sendmessage: '今晚王牌对王牌节目咋样?' } ] // 重载签名 function getMessage(value: number): Message | undefined function getMessage(value: MessageType, linmit?: number): Message[] // 实现签名 function getMessage(payload_: number | MessageType, linmit?: number) { if (typeof payload_ === 'number') { return messages.find((item) => item.id === payload_) } else { const result = messages.filter((item) => item.type === payload_) return (linmit && result.splice(0, linmit)) || result } } console.log(getMessage('audio', 3))
执行时找到匹配的重载签名并执行实现签名中函数体的逻辑
interface OrderType { id: number name: string address: string } class OrderList { constructor(public list: Array<OrderType>) {} removeItem(value: number): number removeItem(value: string): string removeItem(value: OrderType): OrderType removeItem(value: number | string | OrderType) { if (typeof value === 'number') { this.list = this.list.filter((item) => item.id !== value) } else if (typeof value === 'string') { this.list = this.list.filter((item) => item.name !== value) } else { this.list = this.list.filter((item) => item !== value) } return value } } const order1 = new OrderList([ { id: 1, name: '手机', address: '北京' }, { id: 2, name: '电脑', address: '上海' }, { id: 3, name: '桌子', address: '深圳' } ]) console.log(order1.removeItem('手机'), order1.list) export const Test = 1
类动态方法重载
interface ShapeParamType { width: number height: number } class Shape { public radius?: number public width?: number public height?: number constructor(width: number, height: number) constructor(params: ShapeParamType) constructor(radius: number) constructor(paramObjOrValue_: number | ShapeParamType, value_?: number) { if (typeof paramObjOrValue_ === 'object') { this.width = paramObjOrValue_.width this.height = paramObjOrValue_.height // 单值为半径 } else if (typeof paramObjOrValue_ === 'number' && !value_) { this.radius = paramObjOrValue_ } else { this.width = paramObjOrValue_ this.height = value_ } } getArea() { if (this.radius) return Math.pow(this.radius, 2) return this.width! * this.height! } } console.log(new Shape(50).getArea()) console.log(new Shape(50, 10).getArea()) console.log(new Shape({ height: 10, width: 10 }).getArea()) console.log(new Shape({ height: 10, width: 10 }).getArea())
类构造器重载