Skip to content

Instantly share code, notes, and snippets.

@wonderful-panda
Last active February 22, 2018 05:47
Show Gist options
  • Select an option

  • Save wonderful-panda/41362e6173bbe094d9a8cb74fa12811e to your computer and use it in GitHub Desktop.

Select an option

Save wonderful-panda/41362e6173bbe094d9a8cb74fa12811e to your computer and use it in GitHub Desktop.
Generate prop paths of nested module
// marker interface for module
interface Module {
_module_: 1
}
type ValueOf<T> = T[keyof T];
type PropPaths<
T,
K1 extends string = never,
K2 extends string = never,
K3 extends string = never,
K4 extends string = never
> = ValueOf<{
[K in Exclude<keyof T, "_module_">]: (
T[K] extends Module ? (
K1 extends never ? PropPaths<T[K], K> :
K2 extends never ? PropPaths<T[K], K1, K> :
K3 extends never ? PropPaths<T[K], K1, K2, K> :
K4 extends never ? PropPaths<T[K], K1, K2, K3, K> :
never
) : (
K1 extends never ? K :
K2 extends never ? [K1, K] :
K3 extends never ? [K1, K2, K] :
K4 extends never ? [K1, K2, K3, K] :
[K1, K2, K3, K4, K]
)
)
}>;
interface Test {
foo: string;
bar: number;
baz: {
_module_: 1;
hoge: string;
fuga: {
_module_: 1;
piyo: string;
a: {
_module_: 1;
x: {};
},
b: { // is not module
x: {};
}
}
}
}
type X = PropPaths<Test>;
// "foo" | "bar" | ["baz", "hoge"] | ["baz", "fuga", "piyo"] | ["baz", "fuga", "a", "x"] | ["baz", "fuga", "b"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment