typescript - 基于 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');
解决方案
我看到的是您正在混合价值和类型级别。我们需要了解区别,您需要为给定类型分配真实值,您不能只分配一个类型。
我相信这就是您正在寻找的:
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
.
推荐阅读
- elasticsearch - 从日志消息中获取 JSON 子字符串
- azure - 我无法删除天蓝色警报
- java - 服务器端 Omnifaces 推送。PushContext 为空
- kotlin - 如何在 Kotlin 的 .forEach 迭代中获取 Set 中的特定元素
- python - 如何将 pandas 数据框写入现有的启用宏的 Excel 电子表格 (.xlsm)
- python - 参数化泛型不能与类或实例检查一起使用
- python - 将 Python 项目从一台 PC 导出到另一台 PC
- reactjs - 将对象列表作为 proptype 传递
- java - 如何通过 espresso UI 测试初始化演示者的可为空变量以避免 NPE
- biztalk - BizTalk Server 迁移到 2016