首页 > 解决方案 > 动态地将属性绑定到类

问题描述

我想动态创建一个打字稿类并动态添加一个属性给它。

该属性可能是函数或 Promise 或任何其他类型和用途this,我希望this在其中引用该类。

let MyClass = class{
  public property: any;
  public ok = 1;
}


let property = function(){ console.log(this.ok); }

// now we want `this` to refer to MyClass instead of its function


// first trial
MyClass.prototype.property= property;

// second trial: using bind()
// we have another problem here, property not always a fnction
let propertyBind = property.bind(MyClass)


// third trial: add property while creating the class
let MyClass = class{
  public property = property ;
  public ok =1;
}

ifproperty是一个函数,我们不能将this其作为参数传递给它,因为创建的类将提供给第三方,该第三方在没有任何参数的情况下强制执行签名

let property = (this)=>{ console.log(this.ok); }
``

标签: javascripttypescriptclass

解决方案


class BaseClass {
  public property: unknown;
  public ok = 1;
}

function addProperty<Base extends new (...args: any) => any, T>(
  baseClass: Base,
  property: T extends Function ? (this: InstanceType<Base>) => void : T
) {
  return class extends baseClass {
    public property = property;
  };
}

const MyClass1 = addProperty(BaseClass, "hello");
const myClass1 = new MyClass1();
console.log(myClass1.property); // "hello"

const MyClass2 = addProperty(BaseClass, function () {
  // here `this` has type BaseClass
  this.ok++;
});
const myClass2 = new MyClass2();
myClass2.property();
console.log(myClass2.ok); // 2

推荐阅读