open-ended function arguments with TypeScript

后端 未结 3 984
灰色年华
灰色年华 2020-11-28 05:23

IMO, one of the main concerns of the TypeScript language is to support the existing vanilla JavaScript code. This is the impression I had at first glance. Take a look at the

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 06:11

    The TypeScript way of doing this is to place the ellipsis operator (...) before the name of the argument. The above would be written as,

    function sum(...numbers: number[]) {
        var aggregateNumber = 0;
        for (var i = 0; i < numbers.length; i++)
            aggregateNumber += numbers[i];
        return aggregateNumber;
    }
    

    This will then type check correctly with

    console.log(sum(1, 5, 10, 15, 20));
    

提交回复
热议问题