AJP AJP - 7 months ago 39
TypeScript Question

Setting default value for TypeScript object passed as argument

function sayName(params: {firstName: string; lastName?: string}) {
params.lastName = params.lastName || 'smith'; // <<-- any better alternative to this?
var name = params.firstName + params.lastName

sayName({firstName: 'bob'});

I had imagined something like this might work:

function sayName(params: {firstName: string; lastName: string = 'smith'}) {

Obviously if these were plain arguments you could do it with:

function sayName(firstName: string, lastName = 'smith') {
var name = firstName + lastName;


And in coffeescript you have access to the conditional existence operator so can do:

param.lastName ?= 'smith'

Which compiles to the javascript:

if (param.lastName == null) {
param.lastName = 'smith';


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}){
    var name = first + " " + last;

sayName({firstName: '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;