tannerntannern / ts-mixer

A small TypeScript library that provides tolerable Mixin functionality.
MIT License
384 stars 27 forks source link

how to initiate the property of super classes #61

Closed bodycombathuang closed 1 year ago

bodycombathuang commented 1 year ago

I have code like import { Mixin } from 'ts-mixer';

class Foo { public a: string; protected makeFoo() { return 'foo'; } public constructor(a:string) { this.a = a } }

class Bar { public b: string; public c: string; public constructor(b:string,c:string) { this.b = b this.c = c; } protected makeBar() { return 'bar'; } }

class FooBar extends Mixin(Foo, Bar) { public constructor() { super("a") } public makeFooBar() { return this.makeFoo() + this.makeBar(); } }

const fooBar = new FooBar();

how can I set value to property "a" of super class Foo and properties b and c of super class Bar in constructor of FooBar?

if I use super("value") then, both a and b will have value "value" what if I want to assign different value to a, b and c in constructor of FooBar?

tannerntannern commented 1 year ago

ts-mixer expects the class constructors to be compatible with each other. This for loop from the ts-mixer source might shed some light on how it works internally. Basically it just passes the same arguments to every class passed to Mixin(...).

How you resolve this issue is up to you. I would argue that if Foo & Bar need different constructor arguments, then inheritance is the wrong pattern here. They should be composed rather than mixed ("composition over inheritance"). If this is not possible for your case, you could consider reassigning this.a and this.b after calling super(...) depending on what super(...) does.

I'm closing this because this is more of an issue with multiple-inheritance in general, not just ts-mixer. You'd have the exact same problem in Python, which supports mixins natively.