Multiple inheritance with Typescript and class mixins
Jun 1, 2020 11:31 · 219 words · 2 minute read
The Problem : extending more than 1 class in Typescript
This is common use case scenario in OOP hovewer in Typescript & Javascript a slight hack is required.
The solution: Mixins
Are functions that return class constructors so let us dive into example:
Mixin file
In the Gist above, we first declare Class Constructor type that will implement our interfaces which will basically define types (class) constructors that will be returned (Disabled, HasValue). Next we declare mixin functions themselves. In both cases same thing occurs, we implement different interface and set the corresponding property (isDisabled / value) to the new class constructor.
Using mixin in an angular component class
Above the component definition we first declare BaseClass that will be passed to our mixin functions. Next we declare const _MixinDemoBase that has our mixin type constraints (DisabledCtor & HasValueCtor & typeof MixinDemoBase) and stores returning value from mixin function calls. After that we extend our component with _MixinDemoBase and implement interfaces Disabled, HasValue so the typescript in template can pick up our 2 new props. Take note how we mark inputs: [‘isDisabled’, ‘value’], in our component metadata so we can pass values to those props when using component.
Putting it all together
We pass values to both inputs.