有人可以向我解释为什么这样做:
interface M {
(a: number): any;
(a: number[]): any;
}
const foo: M = (a) => {
if (Array.isArray(a)) {
return a.map((num) => num > 0 || num === 0 ? num : num * -1)
} else {
return a > 0 || a === 0 ? a : a * -1;
}
}
如果我将界面更改为
interface M {
(a: number): number;
(a: number[]): number[];
}
这似乎很合乎逻辑,我收到以下错误
Type '(a: number | number[]) => number | number[]' is not assignable to type 'M'.
Type 'number | number[]' is not assignable to type 'number'.
Type 'number[]' is not assignable to type 'number'.
我不明白...
该类型
any
与任何其他类型兼容。因此,第一个选项有效。第二个选项指定返回值的具体类型。问题是在这种情况下,实现必须同时满足所有重载。
也就是说,两者 和 必须同时返回
number
。number[]
在打字稿中,只有在用作any
返回值时才有可能:操场