问个 ts 函数重载的问题?
private handleParams(method: Method.Add, params: AddParams)
private handleParams(method: Method.Reduce, params: ReduceParams)
private handleParams(method: Method, params: AddParams | ReduceParams) {
switch (method) {
case Method.Add:
// 到了这里
// params 还是 AddParams | ReduceParams 这个类型
// 预期是 AddParams 类型,应该怎么写呢
break;
// ...
}
回复
1个回答

test
2024-07-15
- 我不确定问题描述无效的产生原因;
- 可以参考如下写法,看是否可以满足你的需求;
enum Method {
Add = 'Add',
Reduce = 'Reduce',
}
interface AddParams {
method: Method.Add;
name: string;
}
interface ReduceParams {
method: Method.Reduce;
length: number;
}
class Aaa {
private handleParams(params: AddParams): string;
private handleParams(params: ReduceParams): number;
private handleParams(params: AddParams | ReduceParams): number | string {
const method = params.method;
switch (method) {
case Method.Add:
return params.name;
case Method.Reduce:
return params.length;
default:
return 0;
}
}
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容