Создать класс, который пересекает аргумент конструктора, типизированный как Object - PullRequest
0 голосов
/ 19 сентября 2019

Я в основном хочу, чтобы мой класс был любым вводимым объектом, плюс любые дополнительные методы, объявленные в классе.

Свойства объекта могут быть любыми и могут иметь любое имя при создании класса.

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

1 Ответ

1 голос
/ 19 сентября 2019

вариант 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)
}
...