typescript 中的扩展运算符怎么可以正确设置类型推导

function *createrNumber() {
  yield 1;
  yield 2
}
const angle3 = Math.atan2(...createrNumber());

这段代码如果在 js 运行时没有问题的,但是在 ts 上会报类型错误
请问一下对于这样的代码应该怎样正确地设置类型

阅读 2.9k
1 个回答

主要是 Math.atan2 方法参数不支持 ... 运算, 你可以全局类型声明文件中扩展一下 Math.atan2 , 具体如下:

interface Math {
    atan2(...args: number[]): number;
}

TypeScript Playground 传送门

也可以在你的模块文件中添加以下声明

declare global {
  interface Math {
    atan2(...args: number[]): number;
  }
}

不过 Math.atan2 也就两个参数,做类型扩展不是很划算

推荐问题