Search code examples
mixinstsctypescript3.0

How to represent mixins with TypeScript


I am writing a custom mixin routine, it accepts varags of objects:

type HasIndex = {[key:string]:any};

// type RetType = ?

const mixinAll = (...v: HasIndex[]): RetType => {
   return v.reduce((a,b) => doMixing(a,b,new Set()), {});
});

so my question is - how can I represent the return value for mixinAll? Is there a way to represent a mixin type with TypeScript? Very similar to doing the same for Object.assign.


Solution

  • If you look at the definition for Object.assign, that pretty much answers the question:

    interface ObjectConstructor {
     assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
    }
    

    in short, use the & operator to create an intersection type - unfortunately can't seem to create something finer-grained than that.