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
I've found two alternatives solutions inspired in:
1) Solution class Hero: https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#improved-checking-for-destructuring-object-literal
2) Solution class Hero2: section "Optional Properties" https://www.typescriptlang.org/docs/handbook/interfaces.html
import { Component, OnInit } from '@angular/core';
interface HeroInterface {
// you need add ? for each variable (Optional Properties)
id?: number;
name?: string;
}
// Class using solution 1
class Hero {
id: number;
name: string;
//without interface: constructor({id= 3, name= 'defaulthero'}: {id?: number, name?: string } = {}) {
constructor({id= 4, name= 'Spiderman'}: HeroInterface = {}) {
this.id = id;
this.name = name;
}
}
// Class solution 2 ,using short way of assign property on constructor()
class Hero2 {
constructor(public config: HeroInterface = {}) { // short way to assign config like this.config = config;
if (!config.id) this.config.id =10;
if (!config.name) this.config.name = 'SuperMan';
}
}
@Component ( {
selector: 'my-app',
template: `hero1: id: {{hero.id}} name: {{hero.name}}
hero2: id: {{hero2.config.id}} name: {{hero2.config.name}}
`
})
export class AppComponent implements OnInit {
hero: Hero ;
hero2: Hero2 ;
ngOnInit () {
// SOLUTION 1:
// this.hero = new Hero ();
this.hero = new Hero ( { id:9 });
// SOLUTION 2:
this.hero2 = new Hero2 ( ); // Works with default values
//this.hero2 = new Hero2 ( { id: 20} ); // Works with default name value
//this.hero2 = new Hero2 ( { id: 20, name: 'Asterix'}); // send all values, don't need use default values
//this.hero2 = new Hero2 ( { id:19 , name: 'Asterix', weight:90}); // Error, 'weight' does not exist in type 'HeroInterface'
}
}