Destructured parameter properties in constructor

后端 未结 3 1094
情歌与酒
情歌与酒 2020-12-20 12:37

Typescript allows parameter properties

class ParameterProperty {
  constructor(private member: number) {}
}

The above creates a class with

相关标签:
3条回答
  • 2020-12-20 13:19

    What about:

    class Destructed {
        private prefix: string;
        private suffix: string;
    
        constructor(opts: DestructedOptions) {
            Object.assign(this, opts);
        }
    }
    

    Also, there's an open issue on this: Combining destructuring with parameter properties


    Edit

    If you want to avoid re-writing the properties in the class then you'll need to make the members public, when that's the case then the solution is as shown in the issue I linked to:

    class Destructed {
        constructor(opts: DestructedOptions) {
            Object.assign(this, opts);
        }
    }
    
    interface Destructed extends DestructedOptions { }
    
    let destructed = new Destructed({ prefix: "prefix", suffix: "suffix" });
    console.log(destructed.prefix);
    console.log(destructed.suffix);
    console.log(destructed.DoesntExist); // error
    

    (code in playground)

    0 讨论(0)
  • 2020-12-20 13:23

    In ECMAScript, destructuring assignment results in variables in variables (not properties than properties) receiving the component values.

    There has been a TypeScript feature request/suggestion for combining destructuring with parameter properties open since October of 2015. That would probably be the most effective place to track the status of whatyou want.

    0 讨论(0)
  • 2020-12-20 13:26

    There's no obvious, direct way to do what you want. Consider holding options in your class instead of individual properties, as in

    interface DestructedOptions {
      prefix: string;
      suffix: string;
    }
    
    class Destructed {
      constructor(public options: DestructedOptions) {}
    }
    
    <!-- in template -->
    Prefix is {{options.prefix}}!!
    
    0 讨论(0)
提交回复
热议问题