Repository navigation
feature request: support for mixins composed from other mixins. #32080
Description
Search Terms
Suggestion
At the moment, it seems to be very difficult to compose mixins from other mixins.
Here's an example on StackOverflow: https://stackoverflow.com/questions/56680049
Here's an example on playground.
The code:
type Constructor<T = any, A extends any[] = any[]> = new (...a: A) => T
function FooMixin<T extends Constructor>(Base: T) {
return class Foo extends Base {
foo = 'foo'
}
}
function BarMixin<T extends Constructor>(Base: T) {
return class Bar extends FooMixin(Base) {
test() {
console.log(this.foo) // PROBLEM: this.foo is 'any' =(
}
}
}Use Cases
To make it simpler to make mixins (and compose them) like we can in plain JavaScript.
I'm porting JavaScript code to TypeScript, and the JavaScript makes great use of mixins (including composing new mixins from other mixins), but the composition ispractically impossible to do in TypeScript without very tedious type casting.
Examples
Here is the plain JS version of the above example:
function FooMixin(Base) {
return class Foo extends Base {
foo = 'foo'
}
}
function BarMixin(Base) {
// BarMixin is composed with FooMixin
return class Bar extends FooMixin(Base) {
test() {
console.log(this.foo) // this.foo is obviously inherited from FooMixin!
// ^--- This shoud not be an error!
}
}
}It seems to me, that the type checker can realize that the class returned from FooMixin(Base) will be a typeof Foo. The type system could at least be able to allow the Bar class to use methods and properties from Foo, despite not knowing what the Base class will be.
You can also imagine this problem gets worse with more composition, f.e.
return class Bar extends Foo(Baz(Lorem(Ipsum(Base)))) {It should also be possible to constrain the constructor to inherit from a certain base class. For example, the following doesn't work:
(EDIT: this part may actually be moved to a separate issue)
(EDIT 2: this part seems to be resolved)
// Think about Custom Elements here:
function FooMixin<T extends typeof HTMLElement>(Base: T) {
return class Foo extends Base {
test() {
this.setAttribute('foo', 'bar')
}
}
}As Titian Cernicova-Dragomir (@dragomirtitian) pointed out on SO, there are workarounds, but they appear to be very complicated and impractical.
Here's a more realistic example of what I'm doing in JS (and trying to port to TS): I'm using a Mixin() helper function, as a type declaration for the following example, which in practice implements things like Symbol.hasInstance to check if instances are instanceof a given mixin, prevents duplicate mixin applications, and other features, but the types don't work:
type Constructor<T = any, A extends any[] = any[]> = new (...a: A) => T
type MixinFunction = <TSuper>(baseClass: Constructor<TSuper>) => Constructor<TSuper>
// this function does awesome: ensures mixins aren't applied
// more than once on a prototype chain, sets up Symbol.hasInstance so that
// instanceof checks works with any mixin application, etc.
declare function Mixin<T extends MixinFunction>(
mixinFn: T,
DefaultBase?: Constructor
): ReturnType<T> & {mixin: T}
function FooMixin<T extends Constructor>(Base: T) {
return class Foo extends Base {
foo = 'foo'
}
}
const Foo = Mixin(FooMixin)
type Foo = typeof Foo
function BarMixin<T extends Constructor>(Base: T) {
return class Bar extends Foo.mixin(Base) {
bar = 'bar'
test() {
this.foo = 'foofoo' // should work!
}
}
}
const Bar = Mixin(BarMixin)
class Baz extends Bar {
test() {
this.bar = 'barbar' // should work!
this.foo = 'foofoo' // should work!
}
}
const f: Foo = new Bar()Is there a way to do this currently, that we may have missed? (cc: Justin Fagnani (@justinfagnani))
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
Activity
sandersn commentedon Jun 26, 2019
Joe Pea (@trusktr) For your first example, you just need a couple of type annotations to get rid of errors:
For your second example, you can't use
typeof HTMLElementdirectly because its constructor is too restrictive to fit Typescript's mixin pattern. But you can just create a similar type, whichtypeof HTMLElementhappens to be assignable to:I haven't read your full example or Titian Cernicova-Dragomir (@dragomirtitian)'s suggested workaround on SO. Let me do that now.
trusktr commentedon Jun 26, 2019
I don't quite understand. Why does your first example work, and mine (with the
Constructortype, doesn't? It's not immediately clear. Seems as if I'm specifying basically the same thing.trusktr commentedon Jun 27, 2019
How come when I change your example from
to
it no longer works?
sandersn commentedon Jun 27, 2019
There's a hard-coded requirement the mixin's type must be an object type, which
Ctor<{}>is, butT extends Ctor<{}>is not -- it's a type parameter.Using
Ctor<{}>directly may be enough for you;T extends Ctor<{}>is treated likeCtor<{}>insideFooMixin, and when you callFooMixin, anything assignable toT extends Ctor<{}>is also assignable toCtor<{}>.The only reason you'd need a type parameter is to make other parameters of FooMixin use type
T. For example, if you wanted to mixin two things, you could make those two have the exact same type:function FooMixin<T extends Ctor<{}>>(Base1: T, Base2: T). That's weird! Although, there might be more believable examples.trusktr commentedon Jun 30, 2019
Nathan Shively-Sanders (@sandersn) I tried your recommendation with the
HTMLElement, but seems I can't do it with a default arg. For example:but with the
= HTMLElementdefault arg it says:It doesn't make sense to me. How does
HTMLElementnot fit the constraint?trusktr commentedon Jun 30, 2019
Here's another example of better support needed for mixins. In my previous comment,
WithUpdateMixinis for Web Components. At minimum, theBaseneeds to be one of the builtin element classes likeHTMLElement,HTMLDivElement, etc.But the
Baseclass could also be a Custom Element that extends from one of those builtin classes.So in my code (converting from JavaScript), I have the following conditional, in case the
Baseclass has anattributeChangedCallbackmethod (if it is a Custom Element):but TypeScript gives the error:
Obviously it doesn't exist on HTMLElement.
I also tried
but it is invalid syntax for TS.
Same problem with
etc.
I also tried putting
this: anyin the method signature which has the above conditionals, but no luck.How can we make this work?
trusktr commentedon Jun 30, 2019
Alright, I'm trying to work around the problem by forcing a cast, but it isn't making sense. I'm trying:
and it says
Clearly
Tis constrained toT extends Constructor<HTMLElement>, so it seems that therefore it is a constructor and I shouldn't get a type error.Is this simply beyond what is implemented in TypeScript? Does TypeScript need a new feature here?EDIT: Okay, I see
PossibleCustomElementis the instance type. So I got a little closer, but no cigar:and now the error is:
So now my question seems to be valid: Should it be able to understand that an instance of
PossibleCustomElementConstructor<T>(which is constrained to extend from the HTMLElement constructor) should at least have the methods and properties from fromHTMLElementandPossibleCustomElement?trusktr commentedon Jun 30, 2019
Ah! I figured it out.
The problem was: I was intuitively thinking that the constraint
T extends Constructor<HTMLElement>would make((Base as unknown) as PossibleCustomElementConstructor<T>)in my previous comment work, because I had assumed the type system would understand the constraint and implicitly limit the application ofPossibleCustomElementConstructor<T>toPossibleCustomElementConstructor<HTMLElement>. Turns out, I was being too smart for the type system! 🤓 (Maybe this is a new feature request then).So, I figured out that if I explicitly specify the constrained type, instead of intuitively passing T along, then it works, like follows:
And now that makes sense: I know that the type is at least
HTMLElement, so if I explicitly state that in theextendspart of the mixin class, then I know that's what I will at least get (as far as types that I can use inside of theWithUpdateclass.I think it would make sense for TypeScript to infer what I was trying to do by passing
Talong, instead of having to specifyHTMLElementin more than one place; it would make things more DRY.But I still don't like the
as unknowncast; I feel like that shouldn't be there. (Although the combination of the words "unknown" and "PossiblyCustomElement" ironically fit together because we don't know what Base will be exactly).trusktr commentedon Jun 30, 2019
Now I need to figure out if the main thing in the original post is possible: making mixins composed of mixins...
The issue I forsee is that WithUpdate could be mixed with other mixins that don't necessarily extend from HTMLElement, so that later the composed mixin could finally be mixed with a subclass that does extend HTMLElement.
trusktr commentedon Jun 30, 2019
Thanks for your hints about
T extends Ctor<{}>. That helped a lot. I've gotten my mixins working (after many permutations of tinkering to understand how the type checker works), however it still requires a cast because the base class "is not a constructor function type". I found it easier to write my ownConstructorhelper, with defaultT = object, which is what I need in most cases.Basically, here's what a simplified version looks like:
playground
The
as Constructorcast doesn't seem intuitive, but needed when usingTin order to return the mixin type combined with the passed-in constructor type.RyanCavanaugh commentedon Aug 22, 2019
Joe Pea (@trusktr) What further action is required here in your judgment?
trusktr commentedon Nov 17, 2019
Ryan Cavanaugh (@RyanCavanaugh) I think that Mixins need to be made easier. Taking the previous comment's example,
Base as unknown as Constructorreturn Bar as typeof Bar & TIt gets more complicated when adding more mixins into the mix, when the constraint on T is more specific, when needing to include static properties in the return type, etc.
For a look at how complicated and brittle the mixin boilerplates can get, see for example infamous/src/core/Node.ts (you should be able to clone, npm install, and then see all the types in VS Code if there hasn't been any breaking changes in
typescript, it's been a while).trusktr commentedon Dec 28, 2019
I closed #32004 as a duplicate of this one.
trusktr commentedon Aug 3, 2020
It'd be great if mixins in TypeScript were easier. Here's another playground example, and the code:
In particular, notice that
this.oneandthis.twoare typeanyinside thetest()method.ShaMan123 commentedon Dec 6, 2022
+1
Joe Pea (@trusktr) thanks so much for posting all your tryouts!
I've spent too long on this (I am embarrassed to say, around 6 hours), this thread was what saved me.
I encountered a complex case of generic classes that are mixed as base classes.
TS went mad and so did I.
mixin generics fix
jahorton commentedon Dec 30, 2023
I've been experimenting a bit with mixins lately and believe I've run into a related case. As the example code might be a bit large due to the setup, a brief explanation:
I'm looking to create mixins for a class intended for serialization and deserialization in certain cases. Serialization of mixin data isn't too hard of an ask, but the deserialization process for a mixin-enhanced version of the class - that seems to be the hard part, as I want to do it through
staticmethods to preserve proper encapsulation of instances, avoiding exposure of a potentially-incomplete instance. (This can be especially noteworthy for types that are designed to act immutable.)To be explicit, I consider a requirement of preknowledge of the set of mixins involved to be reasonable. (No mixin-inference during deserialization.) I'm looking to deserialize from the final, fully mixed-in class.
I believe I've actually found a way forward on this, though there's one last caveat I wasn't able to completely polish. I've kept a bit of noise in case the variations on things I attempted leading up to this could be enlightening.
Playground example
I managed to get the mixins working with references to static methods declared by the base class; they even redirect to variants defined on intermediate mixins! The main issue - the final return value from the deserialization method has incomplete type inference in a manner very much in line with other cases I noticed on this issue.
Related highlight from my example:
Note: the static method is returning the same type as the mixin, based on the generic parameter
<T extends ...>, as noted to be a possible issue in the first comment of this issue. I'm not sure it's easy or wise to eliminate it though - I fully want the two mixins to be orthogonal, and this allows the intermediate properties to flow through for normally-constructed instances.The other main link that led me to this issue: #32080 (comment). I noticed that that comment's example
one()andtwo()were absent due to mixin composition - these were composited within theThreemixin. In my example code above,IntermediateMixinis (obviously) the composited mixin, and it's the one with the missing property and method. In particular, in this case, the static method's return type returns an object whose typing refers to that of another mixin... which is the same type as the static method's class - but TS is unable to infer this at present.Fortunately, it's possible to work around this oddity with a cast, but it does make the deserialization process a bit more verbose than desired.
jahorton commentedon Dec 30, 2023
What I noticed there gave me an idea: what if the
ConfigConstructorclass there were generic, with a type parameter that adapts to the expected return type for its constructor & static methods?Well... it was worth a shot; we actually get more errors this way. But... those might be enlightening?
The error from the noted line:
Note:
class MixinCore extends Base, with the mixin's parameter defined asBase: T. There's a very clear relation here -class MixinCore extends T- but the inference engine isn't connecting the dots.This is likely due to the generic-param
T, as opposed to the parameterBaseof typeT. At least, that's my personal guess.This error and related behaviors also appear to prevent actually applying the mixin; the genericized class that props up the static method pseudo-inheritance is thus not viable.
Error when attempting to use the mixin with this code variant:
That final line is a fun read. Essentially, "the type doesn't provide its own constructor"? Perhaps that's from the constructor-signature shenanigans I had to pull to meet the base mixin constructor requirements... except no, it persists even if that's the exact signature for the real constructor.
bradyoactive commentedon Feb 16, 2024
Joe Pea (@trusktr) I think the problem with your initial example and the example in #32080 (comment) doesn't explicitly have to do with mixins: It's that you are using
anyas the instance type of yourConstructortype instead of object. In both case, if you changetype Constructor = new (...a: any[]) => anytotype Constructor = new (...a: any[]) => object, everything works as expected. TS playground 1, TS playground 2When Typescript merges the instance types of these constructors, everything is just getting collapsed into
any, more because of howanybehaves than anything specific to constructors.