Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Object Destructuring to Assign Class Members

Tags:

typescript

I am currently in the process of converting come legacy code into typescript for a project. The project contains a number of custom classes written in pure javascript which follow the same pattern of having a constructor which takes in a config object which can have many configuration options defined within it.

I've been toying with how to define the allowed config properties in typescript and haven't yet come up with a solution I'm entirely happy with. I started by declaring an interface for the config, which allows me to define the config options available but doesn't help with defaulting them - I have to copy my config interface twice or more for both the definition and the initialisation. What I (think I) want is to use object destrcuturing to define the class members once with default values and not have to worry about it after that e.g:

export interface MyClassConfig {
    propA: string;
    propB: boolean;
}

export class MyClass {
    private propA: string = 'defautValue';
    private propB: boolean;

    constructor (config: MyClassConfig) {
        { propA, propB } = config;
    }
}

Which could then be initialised with something like:

let mc = new MyClass({ propB: false });   //mc.propA == 'defaultValue', mc.propB === false

I don't like that this requires me to copy the property names multiple times though. Can anyone suggest a nice clean way to achieve this?

like image 515
Samih Avatar asked Oct 17 '22 07:10

Samih


1 Answers

I was facing the same problem: Destructuring and assigning to class members.

I've found the following solution that meets my needs and maybe yours:

interface MyClassConfig {
    propA?: string; // Note the '?' for optional property
    propB: boolean;
}

class MyClass {
    private propA: string = 'defautValue';
    private propB: boolean;

    constructor (config: MyClassConfig) {
        ({ propA: this.propA = this.propA, propB: this.propB } = config);
    }
}

const myClass = new MyClass({ propA: 'aaa', propB: true });
console.log(myClass)

// MyClass:
//   propA = 'aaa';
//   propB = true;

const myClass2 = new MyClass({ propB: false });
console.log(myClass2)

// MyClass:
//   propA = 'defaultValue';
//   propB = false;

See MDN Destructuring assignment chapter "Assigning to new variables names and providing default values".

See JSBin for a working sample

like image 109
passerby Avatar answered Oct 20 '22 23:10

passerby