pocesar
pocesar

Reputation: 7050

Making a mixin of interfaces in Typescript

I have a class with over 80 methods, and each method accepts an object containing some defined interface.

class Stuff {
   /* many more */
   getAccount(req: IAccount, callback: ICallback) {
      return this._call('getAccount', req, callback);
   }

   getIds(req: IIDs, callback: ICallback) {
      return this._call('getIds', req, callback);
   }
   /* many more */
}

pretty 'boring' stuff, since it's just mapping to the underlaying _call method and making it type safe for each of the methods.

But sometimes these req param objects are made up from 2 interfaces or more, and instead of creating another interface for each time there's an "awkward", like this:

export interface ILoled extends IAccount {
   loled: boolean;
}

export interface IRofloled extends ILoled {
   rofled: boolean;
}

class Stuff {
  getLols(req: ILoled){
  }

  getRofls(req: IRofloled){
  }
}

is there any way I can just put it as an "inline" mixin of interfaces inside the method parameter list? like (which obviously don't work):

class Stuff {
  getMoreStuff(req: <{} extends IAccount, ITime>) {
  }
}

Upvotes: 14

Views: 10747

Answers (2)

JasonS
JasonS

Reputation: 7733

Yes you can, as of Typescript 1.6. Called Intersection types, use the & operator to combine types.

function extend<T, U>(first: T, second: U): T & U {
  let result = <T & U> {};
  for (let id in first) {
    result[id] = first[id];
  }

  for (let id in second) {
    if (!result.hasOwnProperty(id)) {
      result[id] = second[id];
    }
  }
  return result;
}

var x = extend({ a: "hello" }, { b: 42 });
x.a; // works
x.b; // works 

Upvotes: 24

basarat
basarat

Reputation: 275849

is there any way I can just put it as an "inline" mixin of interfaces inside the method parameter list

No. You cannot extend an interface inline

Upvotes: 2

Related Questions