Default Arguments and Variable Arguments in Typescript

For my money, the Typescript language is a great way to extend JavaScript, while still transpiling into functional (and readable) JavaScript.

Case in point – default and variable arguments.  Default arguments assign a default value to a function’s parameters so you do not need to specify every parameter when calling.  In JavaScript, a quick conditional is all you need to create a default value:


function DefaultValue(a) {
    a = typeof a !== 'undefined' ? a : "My Default";
}

While simple, there are a number of places you can screw it up.  In TypeScript, you can simply do away with the conditional and assign the default directly to the parameter:


function DefaultValue(a = "My Default") {
}

No more accidently typing “undeifned” only to discover your error in production.  The TypeScript compiler ensures the correct JavaScript is generated for you.

Typescript even supports a simplified version of variable arguments.  Variable arguments are when you don’t know ahead of time how many parameters will be passed to your method, but you still want to be able to handle them.  In JavaScript, you can access variable arguments using the pre-defined variable “arguments”:


function VariableArguments() {
    for (var i = 0; i < arguments.length; i++) {
        arguments[i]; // do something with each argument
    }
}

Again, not complicated, but error-prone and opaque (the function signature does not tell you the method accepts arguments).  In contrast, Typescript makes the variable arguments explicit:


function VariableArguments(...p:any[]) {
    for (var i = 0; i < p.length; i++) {
        p[i]; // do something with each argument
    }
}

The “…p” indicates that the method accepts a variable number of arguments – just make sure that you type it as any array.  Since its TypeScript, you can even indicate that you only accept a specific type by indicating the type of the array in the signature.

Once again, the compiler will ensure that the correct JavaScript is generated and you can focus on your actual software.