JGoodgive
JGoodgive

Reputation: 1126

How to write typescript mixins and get declarations from tsc

I am unable to compile without errors since this Mixin construct with anonymous class in it throws.

export type Constructor<T> = new (...args: any[]) => T;
export interface IFooable {}
export default function FooableMixin<T extends Constructor<{}>>(Base: T) {
    return class extends Base implements IFooable {
        constructor(...args: any[]) {
            super(...args);
        }
    }
}
export class BaseBar {}
export class FooableBar extends FooableMixin ( BaseBar ) {}

When compiling this with tsconfig parameter declaration = true I get TS4093, TS4020 and TS4060. Without the parameter it works fine but then I don't get any declarations.

It seems to be because the anonymous class cannot be exported (made public).

Is there a better way of writing mixins or a better way to get declarations out?

Upvotes: 0

Views: 371

Answers (1)

JGoodgive
JGoodgive

Reputation: 1126

Typescript Issue 15001

This is due to a limitation in Typescript and there are several (now closed) issues on this. The workaround for now that worked for me was to define the return type of the MixinFunction as T & ICtor> to get around TS 4060.

export default function FooableMixin<T extends Constructor<{}>>(Base: T): T & Constructor<IFooable<T>> {

But since we are not alowed to extend from union types directly I then had to:

export const _FooableBar = Fooable(BaseBar);
export class FooableBar extends _FooableBar 

This is messy and hopefully will be solved.

Upvotes: 1

Related Questions