【发布时间】:2021-12-20 16:28:12
【问题描述】:
如何嵌套使用泛型的相同类型?
interface programConfig<T extends Record<string, any>> {
// other types removed; not relevant to the question
commands?: { [key: string]: programConfig<???> }; // how do I type this?
}
更完整的ts playground 示例显示了我正在尝试完成的工作
【问题讨论】:
-
您希望这种类型是什么?如果您希望它完全相同,请传入
T。 -
@Chase - 我希望它成为自己的记录。该记录当前是根据调用代码推断出来的。如果我传入
T,那么所有嵌套实例都使用与根实例相同的记录,这不是我想要的。例子应该更清楚 -
我觉得这是不可能的。您需要
commands是通用的,但在 TypeScript 中,只有类型别名、接口、类、构造函数、函数和方法可以是通用的,但属性、对象和值不能。你基本上需要commands?<U>: { [key: string]: programConfig<U> };见github.com/microsoft/TypeScript/issues/17574
标签: typescript generics typescript-generics