open-ended function arguments with TypeScript

后端 未结 3 962
灰色年华
灰色年华 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:00

    In Typescript it is the concept of Rest Parameter, it is the parameter which receives multiple values of similar type.If we target the typescript then we have to write the code ECMAScript 6 standard,then typescript transpiler converts it to its equivalent java script code(which is ECMAScript 5 standard).If we use typescript then we have to use three dot(...) preferx with the restparameter variable name, such as function sum(...numbers: number[]), then it would work.

    Note: Rest Parameter must be last parameter in the parameter list.likewise function sum(name:string,age:number,...numbers: number[]).

    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-11-28 06:26

    In addition to @chuckj answer: You can also use an arrow function expression in TypeScript (is kind of a lambda in Java / .NET)

    function sum(...nums: number[]): number {
        return nums.reduce((a, b) => a + b, 0);
    }
    
    0 讨论(0)
提交回复
热议问题