【问题标题】:TypeScript: mix in plain object into classTypeScript:将普通对象混入类中
【发布时间】:2021-11-27 11:03:51
【问题描述】:

基本上,我正在尝试创建一个动态定义类的函数,该类从传递的对象扩展另一个类。像这样的:

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

这样做的目标是能够编写混入映射状态的 Vue 类组件。像这样:

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

我几乎可以使用 hacks

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

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

但我不能让它扩展 Vue,而且它显然是一个糟糕的解决方案。

【问题讨论】:

  • 请与smartModule分享可重复的示例
  • 这就是我要帮助的......

标签: typescript vuejs2 vue-class-components


【解决方案1】:

您可能可以像这样使用constructor

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);

【讨论】:

    猜你喜欢
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2012-08-02
    • 2021-01-22
    • 2019-08-10
    相关资源
    最近更新 更多