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>) {
}
}
An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.
Mixins are a faux-multiple inheritance pattern for classes in JavaScript which TypeScript has support for. The pattern allows you to create a class which is a merge of many classes. To get started, we need a type which we'll use to extend other classes from.
You can extend from as many interfaces as necessary by separating the interfaces with a comma. You are not required to add any new members to the final interface and can use the extends keyword to simply combine interfaces.
Mixins are hailed as interfaces with behavioral reuse, more flexible interfaces, and more powerful interfaces. You will notice all these have the term interface in them, referring to the Java and C# keyword. Mixins are not interfaces. They are multiple inheritance.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With