Monthly Archives: November 2016

TypeScript : Functions : Default Parameters

Problem

I want a parameter to have a default value in my TypeScript function.

Answer

You can assign a value to a parameter in your parameter list. The value can be any type of object and even functions.

Example


MyFunction(myString: string, myDefaultValue = "This is a string": string) { ... }


MyFunction(myNumber: number, myDefaultValue = getDefaultValue(): any) {...} //could be : string, or anything else

TypeScript : Functions : Optional Parameters

Problem

I need to allow a parameter to be optional in TypeScript. Optional parameters in TypeScript have to be declared.

Answer

Use “?” next to the parameter name to allow the parameter to be optional. The optional parameter must come last in the parameter list but before a REST parameter.

Example

MyFunction(myString: string, myNumberOpt?: number) { ... }