假设我有一个任意深度的TypScript界面,它描述应用程序的状态,如下所示:
interface MyState {
foo: boolean;
bar: {
baz: string;
bur: {
pir: string;
par: { pew: boolean }[]
}
}
}
我现在想写一个类型,允许我约束一个字符串数组,以描述指向遵守该接口的对象中任意点的有效路径.例如,所有这些都应该是正确的:
myPath: PathType<MyState> = ["foo"];
myPath = ["bar", "baz"];
myPath = ["bar", "bur"];
myPath = ["bar", "bur", "par"];
Array handling would be cool like:
myPath = ["bar", "bur", "par", 1, "pew"];
无效:
myPath = ["baz"];
myPath = ["bar", "pir"];
myPath = ["any", "random", "crap"];
我try 过这样的方法:
type PathType<State, Key extends keyof State = keyof State> =
State extends object ?
[Key, ...PathType<State[Key], keyof State[Key]>] : never;
但它们似乎都在回归时失败,只有数组的第一个条目被正确输入,然后它接受所有内容.