JavaScript rest parameter with TypeScript

What are …rest parameters?

…rest parameters are an identifier that represents the name of the array of arguments passed in to the function. The parameter does not need to be called rest; it can have any name that is not a keyword. You can specify the data type of the … (rest) parameter as any[] (Array), but this could cause confusion because the parameter accepts a comma-delimited list of values, which is not identical to an instance of the array.

Below you can see we have two single parameters followed by a …(rest) parameter.

class RestExample
{
    constructor()
    {
        this.restExampleMethod("arg1", "arg2", "Start", "of", "rest", "arguments")
    }

    public restExampleMethod(param1:string, param2:string, ...rest):void
    {
        console.log("param1", param1);//Logs single string.
        console.log("param2", param2);//Logs single string.
        console.log("...rest", rest);//Logs array of strings.
    }

}

Below you can download the TypeScript example files. Also if you like this tutorial please provide a link back to this page or my site.

Leave a Reply