【发布时间】:2021-12-11 02:42:08
【问题描述】:
我想创建一个类型 NestedKeys 迭代给定的嵌套类型 RootNav 并收集值为 Nested<T> 的所有键,并使其成为包含键的字符串的联合类型,同时遵循嵌套结构(也许是递归的?)
type Nav = {
[key: string]: NestedNav<Nav> | object | undefined
}
type NestedNav<T extends Nav> = T
type RootNav = {
LoginNav: NestedNav<LoginNav>;
RegistrationNav: NestedNav<RegistrationNav>;
AppNav: NestedNav<AppNav>
}
type AppNav = {
MainNav: NestedNav<MainNav>;
FooScreen: undefined
BarScreen: {id: string}
};
type LoginNav = {
LoginScreen: undefined
}
type RegistrationNav = {
RegistrationScreen: undefined
}
type MainNav = {
HomeScreen: undefined
ProfileScreen: undefined
}
结果应该是
type NestedKeys<RootNav>
// → "RootNav" | "LoginNav" | "RegistrationNav" | "AppNav" | "MainNav"
我有这样的想法,但不知道如何正确执行。这不起作用:
type NestedKeys<T extends Nav> = T[keyof T] extends NestedNav<any> ? NestedKeys<T[keyof T]> : T```
【问题讨论】:
-
请提供可重现的例子:
NestedNav -
我认为它的外观并不重要。它可以只是一个对象。我认为您需要使用条件类型(扩展)来处理它,以使其他内容有所不同。
-
@captain-yossarian 更新了答案,也许现在对你来说更清楚了。
标签: typescript react-navigation union-types mapped-types nested-types