Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY with TypeScript and constructor that takes options object

I have this code:

export interface LDAPPoolOpts {
  id: number;
  size: number;
  connOpts: any;
  active: Array<any>;
  inactive: Array<any>;
  dn: string;
  pwd: string;
  waitingForClient: Array<Function>
}


export class Pool {

  id: number;
  size: number;
  connOpts: any;
  active: Array<any>;
  inactive: Array<any>;
  dn: string;
  pwd: string;
  waitingForClient: Array<Function>;

  constructor(opts: LDAPPoolOpts) {}

 }

as you can see the constructor for this class simply takes an options object with type: LDAPPoolOpts.

My question is: how can avoid repeating myself by having to declare the exact same fields for both the class and the options object interface?

You cannot extend an interface..and implementing an interface does not mean you inherit the interface's fields.

Should I declare a type instead of an interface?

like image 879
Alexander Mills Avatar asked Dec 09 '25 10:12

Alexander Mills


2 Answers

You are correct in that you cannot extend an interface and implementing the interface requires you to write out the properties again. Although this solution alters the structure of your class, one way is to create a property on the class with the interface type.

export interface LDAPPoolOpts {
    id: number;
    size: number;
    connOpts: any;
    active: Array<any>;
    inactive: Array<any>;
    dn: string;
    pwd: string;
    waitingForClient: Array<Function>
}


export class Pool {
     opts: LDAPPoolOpts;

     constructor(opts: LDAPPoolOpts) {
         this.opts = opts; // assign to the property how you see fit
     }
}
like image 96
Andrew Sinner Avatar answered Dec 11 '25 01:12

Andrew Sinner


What I frequently use is the following:

export class Pool {
    // ...

    constructor(initializer?: Partial<Pool>) {
        if (initializer) {
            Object.assign(this, initializer)
        }
    }
}

This, of course, assumes that the class has the same properties as the supposed initializer object, so this is essentially very similar to object initialization in C#. This approach works best if you are also initializing your instance members to meaningful default values.

like image 24
John Weisz Avatar answered Dec 10 '25 23:12

John Weisz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!