我基本上希望我的类是我输入的任何对象,以及类中声明的任何其他方法。
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)
}