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

后端 未结 3 1934
名媛妹妹
名媛妹妹 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:19

    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

提交回复
热议问题