使用 Spread 运算符时出现 TypeScript 错误? [英] TypeScript error when using the Spread operator?

查看:44
本文介绍了使用 Spread 运算符时出现 TypeScript 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我使用像下面这样的扩展运算符

Whenever I use the spread operator such as below

public drawTextTest(p1: number, p2: number, p3: number):void {
    console.log(p1, p2, p3);
}
let array = [2, 2, 5];
this.drawTextTest( ... array );

我在编辑器中收到此错误

I get this error in the editor

[ts] 需要 # 个参数,但最少为 0.

[ts] Expected # arguments, but got a minimum of 0.

为什么 TypeScript 在使用扩展运算符传递参数时会报错?

Why does TypeScript give an error when using the spread operator to pass arguments?

当我实际运行代码时没有错误,展开运算符只是让我使用数组作为函数的参数,但在 VSCode 中它向我显示了错误,好像我不能.

There's no error when I actually run the code, the spread operator is simply letting me use the array as arguments to a function yet in VSCode it shows me the error as if I couldn't.

推荐答案

typed spread operator 仅在所有参数都标记为 optional 时有效

typed spread operator works only when all parameters are marked as optional

public drawTextTest(p1?: number, p2?: number, p3?: number):void {

参见 https://github.com/Microsoft/TypeScript/issues/4130#issuecomment-303486552

这篇关于使用 Spread 运算符时出现 TypeScript 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆