0

我基本上希望我的类是我输入的任何对象,以及类中声明的任何其他方法。

Object 属性可以是任何东西,并且在构造类时可以命名为任何东西。

// this is the type I want my class to be:
// the input object (T) plus the prototype methods (TestClass)
type MyClass = TestClass & T

如果我想象这样做,我将通过以下方式实现:

class TestClass<T extends Object> {
  constructor(obj: T) {
    // this doesn't work because it wants properties after this
    // this.name, this.wife, etc.
    this = obj
  }
  returnMe(): this & T  {
    return this
  }
}

// This returns the correct type
// but the class itself doesn't have the types added on.
function TestFactory<T extends Object>(obj: T): TestClass<T> & T {
  return new TestClass(obj)
}
4

1 回答 1

1

选项1:

class TestClass {
  // define the methods it needs
}

function TestFactory<T extends Object>(obj: T): TestClass & T {
  return Object.assign(new TestClass(), obj)
}

选项2:

class TestClass<T extends Object> {
  // define the methods it needs
  constructor(o: T) {
    Object.assign(this, o)
  }
}

function TestFactory<T extends Object>(obj: T): TestClass<T> & T {
  return <T>new TestClass(obj)
}
于 2019-09-19T04:50:42.770 回答