【问题标题】:Create class that intersects constructor argument typed as Object创建与类型为 Object 的构造函数参数相交的类
【发布时间】:2019-09-19 00:48:04
【问题描述】:

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

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

【问题讨论】:

    标签: typescript constructor intersection typescript-class


    【解决方案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)
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-21
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 2021-09-23
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      相关资源
      最近更新 更多