Setting default value for TypeScript object passed as argument
Typescript supports default parameters now:
https://www.typescriptlang.org/docs/handbook/functions.html
Also, adding a default value allows you to omit the type declaration, because it can be inferred from the default value:
function sayName(firstName: string, lastName = "Smith") {
const name = firstName + ' ' + lastName;
alert(name);
}
sayName('Bob');
Actually, there appears to now be a simple way. The following code works in TypeScript 1.5:
function sayName({ first, last = 'Smith' }: {first: string; last?: string }): void {
const name = first + ' ' + last;
console.log(name);
}
sayName({ first: 'Bob' });
The trick is to first put in brackets what keys you want to pick from the argument object, with key=value
for any defaults. Follow that with the :
and a type declaration.
This is a little different than what you were trying to do, because instead of having an intact params
object, you have instead have dereferenced variables.
If you want to make it optional to pass anything to the function, add a ?
for all keys in the type, and add a default of ={}
after the type declaration:
function sayName({first='Bob',last='Smith'}: {first?: string; last?: string}={}){
var name = first + " " + last;
alert(name);
}
sayName();
Object destructuring the parameter object is what many of the answers above are aiming for and Typescript now has the methods in place to make it much easier to read and intuitively understand.
Destructuring Basics: By destructuring an object, you can choose properties from an object by key name. You can define as few or as many of the properties you like, and default values are set by a basic syntax of let {key = default} = object
.
let {firstName, lastName = 'Smith'} = myParamsObject;
//Compiles to:
var firstName = myParamsObject.firstName,
_a = myParamsObject.lastName,
lastName = _a === void 0 ? 'Smith' : _a;
Writing an interface, type or class for the parameter object improves legibility.
type FullName = {
firstName: string;
/** @defaultValue 'Smith' */
lastName ? : string;
}
function sayName(params: FullName) {
// Set defaults for parameter object
var { firstName, lastName = 'Smith'} = params;
// Do Stuff
var name = firstName + " " + lastName;
alert(name);
}
// Use it
sayName({
firstName: 'Bob'
});