Let’s say I have an arbitrarily deep Typescript interface that describes an app’s state like:
interface MyState {
foo: boolean;
bar: {
baz: string;
bur: {
pir: string;
par: { pew: boolean }[]
}
}
}
I now want to write a Typescript type that allows me to constrain an array of strings to describes a valid path to an arbitrary point in an object adhering to that interface.
E.g. all of those should be correct:
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"];
Invalid:
myPath = ["baz"];
myPath = ["bar", "pir"];
myPath = ["any", "random", "crap"];
I have tried approaches like this:
type PathType<State, Key extends keyof State = keyof State> =
State extends object ?
[Key, ...PathType<State[Key], keyof State[Key]>] : never;
But they all seem to fail with the recursion, only the first entry of the array is typed correctly, then it accepts everything.
Any help very much appreciated!