Search code examples
typescriptobjecttypesunion-types

How can I dynamically define a union type that covers all paths of an object in TypeScript?


Image I have this object:

const data = {
  foo: "foo",
  bar: "bar",
  layer1: {
    foo: "foo",
    layer2: {
      foo: "foo",
      bar: "bar",
    },
  },
};

How could I define a union type of strings that has all possible paths (= I mean descending property chains such as foo.layer1.foo or foo.layer1.layer2.bar or also just foo, ...)

I tried lumping together random pieces but can't get any further and don't know how I could do this dynamically... Is there any clever way of doing this?

type Path =
  `${keyof typeof data}.${keyof typeof data.layer1}.${keyof typeof data.layer1.layer2}`;

This is would the type should look like ideally for data:

type Path = "foo" | "bar" | "layer1.foo" | "layer1.layer2.foo" | "layer1.layer2.bar";

Solution

  • I just realized this is probably a duplicate of Typescript: deep keyof of a nested object. I didn't know how to formulate good search queries for this problem. I flagged my question as duplicate of the mentiond post. After a few changes this answer perfectly solved my problem:

    type NestedObjectPaths = Paths<typeof data>;