如何检查传递给函数的参数数量是否错误

How to check for wrong number of parameters passed to a function

我正在编写一个程序,使用 typescript 和 tslint 作为 linter。 我目前最喜欢的规则列表如下 (tslint.json):

{
    "extends": "tslint:recommended",

    "rules": {
        "comment-format": [false, "check-space"],
        "eofline": false,
        "triple-equals": [false, "allow-null-check"],
        "no-trailing-whitespace": false,
        "one-line": false,
        "no-empty": false,
        "typedef-whitespace": false,
        "whitespace": false,
        "radix": false,
        "no-consecutive-blank-lines": false,
        "no-console": false,
        "typedef": [true,
            "variable-declaration",
            "call-signature",
            "parameter",
            "property-declaration",
            "member-variable-declaration"
        ],
        "quotemark": false,
        "no-any": true,
        "one-variable-per-declaration": false
    }

}

尽管我使用的是 Tslint,但它未能捕捉到对参数数量错误的函数的调用。 例如我有以下功能:

let displayTimer: Function = function(): void {
    document.getElementById('milliseconds').innerHTML = ms.toString();
    document.getElementById('seconds').innerHTML = seconds.toString();
    document.getElementById('minutes').innerHTML= minutes.toString();
};

我从另一个函数内部调用它,如下所示:

let turnTimerOn: Function = function(): void {

    ms += interval;

    if (ms >= 1000)
    {
        ms = 0;
        seconds += 1;
    }

    if (seconds >= 60)
    {
        ms = 0;
        seconds = 0;
        minutes += 1;
    }

    displayTimer(1);
};

如您所见,我将一个参数传递给 displayTimer 函数(在本例中为数字 1,但也可以是其他任何参数),而 linter 没有捕捉到它。

只需删除类型 Function,TypeScript 将检查签名:

let displayTimer = function(): void {
    // ...
};

displayTimer(1); // Error: Supplied parameters does not match any signature of call target

displayTimer 的推断类型不是 Function(接受任何签名),而是 () => void

the code in the PlayGround