0

I have something like the following:

const items: {
   get: (name: string) => '-' + name,
   log: () => { console.log('Hello') },
   commands: {
      table: ( name: string ) => 'table-' + name;
      // lots more functions / objects.
   }
  // lots more functions / objects.
}

Is there a way to created a type or interface with all the function names flattened / on one level like this:

interface Items {
   get: ( name: string ) => string;
   log: () => void;
   table: ( name: string ) => string;
}

I've got as far as writing:

type Mapped<T extends Record<string, any>> = {
  [K in keyof T]: T[K] extends Record<string, unknown> ? Mapped<T[K]> : T[K];
};

type Items = Mapped<typeof items>;

But I'm not flattening them into one level. I'm not 100% sure about doing recursively doing this and getting the results on one level.

Ewan
  • 378
  • 3
  • 14
  • What if you have conflicting keys? – kelsny Nov 02 '22 at 18:09
  • Such deeply nested recursive types always have a zillion edge cases that make me want to scream. Does [this approach](https://tsplay.dev/WJXOVN) meet your needs? Please test against your use cases, including any edge cases you might care about, and let me know. If it works for you I could write up an answer explaining; if not, what am I missing? Please mention @jcalz to notify me if you reply. – jcalz Nov 02 '22 at 18:18
  • @jcalz I was thinking about your comment. In response I've asked another question which would be a better solution. https://stackoverflow.com/questions/74302998/typescript-type-map-nested-object-functions-and-flatten-with-prepending-pare – Ewan Nov 03 '22 at 12:24
  • So you don't want an answer here? Maybe you should delete the question. Or delete the other one, since it's essentially just an edit of this question to expand the scope (this question is "how do I write this type" and the other question is "how do I write a more complicated version of this type *and* how do I apply the type to this function"). Let me know how to proceed (ping via @jcalz) – jcalz Nov 03 '22 at 15:07

0 Answers0