如何使用点差作为函数的参数

时间:2019-04-28 06:43:01

标签: typescript

我想通过点差给canvas.context.fillRect一些参数,然后tslint告诉我该函数需要4个参数但得到1,如何解决错误?还是这是我的错误?


    public drawRect(option: RectOption | number[]): CanvasRenderingContext2D {
        let Option: any;
        if (option.constructor === Object) {
            Option = option as RectOption;
            this.ctx.fillRect(Option.x, Option.y, Option.w, Option.h);
        } else {
            Option = option;
            if (Option.length === 4) {
                console.log(Option)
                this.ctx.fillRect(...Option);
            }
        }
        return this.ctx;
    }
    drawRect([325,100,200,200])

1 个答案:

答案 0 :(得分:0)

lib.d.ts声明fillRectfillRect(x: number, y: number, w: number, h: number): void;,比fillRect(rect: number[]);更准确。如果我是您,则选择向该函数显式传递四个数字,这使代码更具语义:

this.ctx.fillRect(Option[0], Option[1], Option[2], Option[3]);

this.ctx.fillRect(...Option as [number, number, number, number]);

无论如何,您需要告诉TypeScript编译器Option是4个长度的数字数组,无法从if(Option.length === 4)if(Option.length === 2+2)推论得出。

顺便说一句,any总是可以的(不会引起编译错误),但是强烈建议不要这样做。

相关问题