TypeScript实现按弹出数量匹配回调入参类型的函数重载咨询
TypeScript pop函数实现问题解决方案
代码疏漏点
- 重载逻辑错误:你将
count为undefined的场景绑定了接收数组的回调,但你设置了count默认值为1,未传count时实际值为1,和重载定义的逻辑完全冲突,导致类型匹配异常。 - 类型收窄失效:TypeScript无法根据
count的判断自动推导回调函数的对应类型,直接调用回调会报参数不匹配的错误。
正确实现代码
// 重载1:显式传count=1,回调接收单个元素 function pop<T>(items: T[], cb: (item: T) => void, count: 1): void; // 重载2:不传count,默认值为1,回调接收单个元素 function pop<T>(items: T[], cb: (item: T) => void): void; // 重载3:count为不等于1的数字,回调接收数组 function pop<T>(items: T[], cb: (item: T[]) => void, count: number): void; // 函数实现 function pop<T>( items: T[], cb: ((item: T) => void) | ((item: T[]) => void), count = 1, ): void { if (count === 1) { (cb as (item: T) => void)(items[0]); } else if (count > 1) { (cb as (item: T[]) => void)(items.slice(0, count)); } else { (cb as (item: T[]) => void)([]); } }
用法示例
// 不传count,默认1,回调参数为单个number类型 pop([1,2,3], item => console.log(item.toFixed())) // 显式传count=1,回调参数为单个number类型 pop([1,2,3], item => console.log(item.toFixed()), 1) // 传count=2,回调参数为number数组类型 pop([1,2,3], items => console.log(items.length), 2) // 传count=0,回调参数为空数组类型 pop([1,2,3], items => console.log(items.length), 0)
内容的提问来源于stack exchange,提问作者Jasper Kuperus
相关产品推荐
相关产品推荐

