Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructured parameter properties in constructor

Tags:

Typescript allows parameter properties

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

The above creates a class with private member member, the constructor sets this.member to the first argument of the constructor.

But there is no equivalent for 'named parameters' via destructuring.

interface DestructedOptions {   prefix: string;   suffix: string; }  class Destructed {   constructor({private prefix, private suffix}: DestructedOptions) {} } 

The above doesn't work, you have to do something like this:

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

which is really verbose and requires updates to three places when adding a new property to DestructuredOptions. I tried something similar, using mapped properties

class Destructed {   private [P in keyof DestructedOptions]: T[DestructedOptions];   constructor(opts: DestructedOptions) {     Object.assign(this, opts)   } } 

Only to find out that mapped properties can only be used in Types, not interfaces or classes. I don't like this option anyway since it copies everything from opts, I would really want something like this:

class Destructed {   constructor(opts: DestructedOptions) {     for (let key in keyof DestructedOptions) {       this[key] = opts[key];     }   } } 

But of course typescript doesn't let you get runtime values from Types.