1

Basically I'm trying to create a function that dynamically defines class that extends another class from passed object. Something like this:

const ObjectMixin = function<T>(obj: T): new () => T {
    return class extends BaseClass {
        ...obj // pseudo code to convey the idea 
    }
}

Goal of this is to be able to write Vue class components with mapped state mixed in. Like this:

class MyComponent extends ObjectMixin(smartModule.mapState(['someState'])) {
    created() {
        this.someState // should not give any errors
    }
}

I almost got it working with hacks

interface ObjMixinI {
    <T>(obj: T): new () => T
}

const ObjectMixin: ObjMixinI = obj =>
//@ts-ignore
    function() {
        //@ts-ignore
        Object.assign(this, obj)
    }

But I can't make it extend Vue plus it's obviously a horrible solution.

2
  • please share reproducible example with smartModule Commented Oct 7, 2021 at 10:43
  • that's what I'm asking to help with.... Commented Oct 7, 2021 at 11:45

1 Answer 1

0

You can probably use the constructor like this:

const ObjectMixin = function<T>(obj: T) {
    return class extends BaseClass {
        constructor() {
            super();

            Object.assign(this, obj);
        }
    } as { new (): BaseClass & T }
}

class X extends ObjectMixin({ test: 42 }) { }
const x = new X();
console.log(x.test);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.