By 06/07/2015 8 Comments

Rest Parameter In TypeScript

The Rest Parameter:

  • In TypeScript we can know whether a function has parameters or not OR another words, the arguments are received by a function or not.
  • Through the rest parameter a TypeScript function can receive any number of arguments and does not generate a compile-time error.
  • The rest parameter is an array which receives the arguments, store them into index order (start from 0) and access them through a loop.
  • The rest array is declared in a function as a function parameter with three dots such as (…restParamName : type [ ] ), here a name can be any meaningful name, type specifies the data-type such as number, string etc. and [ ] square brackets indicates that it is an array.
  • The TypeScript compiler generates the standard’s JavaScript “arguments” keyword from its rest parameter.

Example – 1:

// Following is a void type function declaration which has a rest array of type string as its parameter.
function getNames(...argNames: string[]) {

// For loop which loops through each argument and print.
    for (var index = 0; index < argNames.length; index++) {
        document.write("argNames " + index + " = " + argNames[index] + " <br/> ");
    }
}

// Following, a same function is being called twice.
// function is being called 1st time with 4 arguments.
getNames("TypeScript", "Php", "JavaScript", "Jquery");

// function is being called 2nd time with 2 arguments.
getNames("Css", "Html");

Example – 2:

/* Following is a void type function declaration which has 2 normal parameters and also a rest array of type string as its parameter. Note: a rest parameter array must be declared at last, if we declare it at the beginning of the normal parameter-list TypeScript compiler will generate a compile-time error. */
function getNames(sno:number, xml:string, ...argNames: string[]) {

// For loop which loops through each argument and print.
    for (var index = 0; index < argNames.length; index++) {
        document.write("argNames " + index + " = " + argNames[index] + " <br/> ");
    }

// Print normal parameters.
    document.write("Sno.: " + sno + "<br/>");
    document.write("Programming: " + xml);
}

// function is being called with 6 arguments.
getNames(55, "Xml", "TypeScript", "Php", "JavaScript", "Jquery");





Next Tutorial →


← Previous Tutorial


Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .