Typescript 我们必须输入类型';任何';对于重载函数的每个参数?

Typescript 我们必须输入类型';任何';对于重载函数的每个参数?,typescript,Typescript,我想了解,我们是否必须为重载函数的每个参数输入类型“any”。例如: -我们必须这样做吗 protected func(value: number): void; protected func(value: string): void; protected func(value: any): void { //...implementation } -或者我们可以这样做 protected func(value: number): void; protected func(val

我想了解,我们是否必须为重载函数的每个参数输入类型“any”。例如:

-我们必须这样做吗

protected func(value: number): void;

protected func(value: string): void;

protected func(value: any): void {
    //...implementation
}
-或者我们可以这样做

protected func(value: number): void;

protected func(value: string): void;

protected func(value: number | string): void {
    //...implementation
}

如果第二个例子是正确的,下一个问题是:这是一个更好的方法吗?为什么?

两者都有效,甚至还有第三种选择:

protected func(value: number): void;
protected func(value: string): void;
protected func(): void {
    let obj = arguments[0];
    //...implementation
}
(或
func(…args:any[])

至于什么更好,这取决于你、你的风格和你想要达到的目标。
在您给出的示例中,我将使用:

protected func(value: number | string): void { ... }
但是,例如,像这样的事情:

protected func(value1: number, value2: string[], value3: () => void): void;
protected func(value1: { [key: string]: number }, key: string): void;
protected func(): void { ... }

只需使用
参数
就可以更容易地找到与前两个参数匹配的签名。

据我所知,没有任何区别和“陷阱”,我的选择应该基于我的便利性(应该选择更简单的方式)。是的。没有真正的区别。