首页 > 解决方案 > 基于 TypeScript Generic 设置变量

问题描述

是否可以基于 TypeScript Generic 设置变量?

class Foo<T> {
  constructor() {
    // This doesn't actually work but it's essentially what I would like to do
    const myKey = (T extends number ? 'myNumber' : null);
  }
}

这是一个更完整的示例,可以在外部 IDE 中运行。这里的目标是使用适当的泛型 (Dog | Cat) 实例化Animal该类,同时还使构造函数能够获取从getUpdate. 在下面的示例中,这是通过myKey. 重申一下我原来的问题,有没有办法在实例化类时不让“狗”出现 2 次来执行所有这些操作?

interface Dog {
  bark: string;
}

interface Cat {
  meow: string;
}

type AnimalType<T> =
  T extends Dog ? Dog :
    T extends Cat ? Cat : null;

const getUpdate = (): Record<string, Dog | Cat> => ({
  dog: { bark: 'woof' },
  cat: { meow: 'meow' },
});

class Animal<T> {
  public state!: AnimalType<T>;

  constructor(myKey: 'dog' | 'cat') {
    this.state = getUpdate()[myKey] as AnimalType<T>;
  }
}
// dogInstance is of type `Animal<Dog>` with a state of `{ bark: 'woof' }`
const dogInstance = new Animal<Dog>('dog');

标签: typescript

解决方案


我看到的是您正在混合价值和类型级别。我们需要了解区别,您需要为给定类型分配真实值,您不能只分配一个类型。

我相信这就是您正在寻找的:

class Foo<T> {
  constructor(key: T extends number ? 'myNumber' : null) {
    const myKey = key;
  }
}

const foo = new Foo<number>('myNumber'); // only possible option is 'myNumber'
const fooNull = new Foo<null>(null); // only possible option is null

如您所见,我正在限制参数的实际值并将其传递给myKey.


推荐阅读