首页 > 解决方案 > 有没有办法在打字稿中实例化通用文字类型?

问题描述

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

我想将文字作为通用参数传递,然后实例化它。考虑以下示例:

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();

是否有任何神奇的方法来实例化 Generic 类型而不通过构造函数再次显式提供它?

标签: javascripttypescriptgenericstypescript-generics

解决方案


您可以使用一个中间包装器来处理扩展泛型和调用构造函数:

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


推荐阅读