0

Hi all I'm wondering if somebody could help me.

I have a function that takes each level of an object as a string with a dot seperator

eg

const fooType = {
  test: {
    test1: {
      test2: 'test'
    }
  },
  testing: {
    testable: 'be'
  },
  bottom: 'b'
}; 

so if I wanted to get the value of test2 I would write the function as

foo('test.test1.test2')

if I take the following type fooTypeProps = keyof typeof fooType;

It gives me a union of test | testing | bottom

I'm wondering if there is a way in typescript to get that keyof but for all the layors so In this situation I would have a union of test.test1.test2 | testing.testable | bottom

Kisbys
  • 413
  • 1
  • 3
  • 12
  • There's no type-level string manipulation so the compiler cannot turn `"test"` and `"test1"` into `"test.test1"`. The best you can get is tuples like `["test", "test1", "test2"] | ["testing", "testable"] | ["bottom"]` – jcalz Dec 17 '19 at 01:04

1 Answers1

0

In the question this duplicates you can take your type and get a union of tuples representing the leaves of the tree of paths:

type AllLeaves = Leaves<typeof fooType>
/* type AllLeaves = ["test", "test1", "test2"] | ["testing", "testable"] | ["bottom"] */

Playground link

But you can't convert those into dotted strings in the type system, which has no notion of string literal manipulation.

jcalz
  • 264,269
  • 27
  • 359
  • 360