typescript destructuring object literal in construct of the class, default properties does not work

后端 未结 3 1935
名媛妹妹
名媛妹妹 2021-01-26 05:56

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         


        
3条回答
  •  情书的邮戳
    2021-01-26 06:32

    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' } }

提交回复
热议问题