有没有办法在TypeScrip中实例化泛型文字类型?

我想做一些可能非正统的事情(如果我们诚实的话,也几乎毫无用处),所以我们开始吧:

我希望将文本作为泛型参数传递,然后实例化它。请考虑以下示例:

const log = console.log;

class Root<T = {}> {
  // public y: T = {}; // this obviously doesn't work

  // again this won't work because T is used a value. Even if it worked,
  // we want to pass a literal
  // public y: T = new T();

  public x: T;
  constructor(x: T) {
    this.x = x;
  }
}

class Child extends Root<{
  name: "George",
  surname: "Typescript",
  age: 5
}> {
  constructor() {
    // Duplicate code. How can I avoid this?
    super({
      name: "George",
      surname: "Typescript",
      age: 5
    });
  }

  foo() {
    // autocomplete on x works because we gave the type as Generic parameter
    log(`${this.x.name} ${this.x.surname} ${this.x.age}`); 
  }
}


const main = () => {
  const m: Child = new Child();
  m.foo();
};
main();

这是可行的,但我必须传递两次文本。一次在泛型上用于自动完成,一次在构造函数上用于初始化。啊。

另一种方法是在Child之外声明我的文本。如下所示:

const log = console.log;

class Root<T = {}> {
  // public y: T = {}; // this obviously doesn't work

  // again this won't work because T is used a value. Even if it worked,
  // we want to pass a literal
  // public y: T = new T(); 

  public x: T;
  constructor(x: T) {
    this.x = x;
  }
}

// works but ugh..... I don't like it. I don't want to declare things outside of my class
const literal = {
  name: "George",
  surname: "Typescript",
  age: 5
}
class Child extends Root<typeof literal> {
  constructor() {
    super(literal);
  }

  foo() {
    // autocomplete on x works because we gave the type as Generic parameter
    log(`${this.x.name} ${this.x.surname} ${this.x.age}`); 
  }
}


const main = () => {
  const m: Child = new Child();
  m.foo();
};
main();

是否有什么神奇的方法可以实例化泛型类型,而无需通过构造函数再次显式提供它?


解决方案

您可以使用中间包装器,该包装器同时负责扩展泛型和调用构造函数:

function fromRoot<T>(x: T) {
  return class extends Root<T> {
    constructor() {
      super(x)
    }
  }
}

然后:

class Child extends fromRoot({
  name: "George",
  surname: "Typescript",
  age: 5
}) { etc }

PG

相关文章