I\'m trying to use default values for destructuring object literal, but I don\'t get the default values, just \'undefined\'. What is the right way?
import { Comp
When you don't assign default value for object fields, typescript will treat it as a normal parameter(type of object) like below:
constructor(obj: any = {id:3, name: 'defaulthero'})
when creating a new instance of hero by new Hero(), there will be no parameter for constructor, so the default {id:3, name: 'defaulthero'} will be used.
when creating a new instance of hero by new Hero({}), there will be one parameter which is an object with no fields and it will be used as the income parameter and take the place of default {id:3, name: 'defaulthero'}.(the same as new Hero ( {id: 0} ))
as you have one commented line at your code block, you can assign default value for fields of object parameters with the below changes:
constructor({id=3, name='defaulthero'}: {id?: number, name?: string } = {}) {
this.id = id;
this.name = name;
}
Plunker demo