sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
13.87k stars 527 forks source link

Exclude / Pick type in Paths / only add leaf nodes #860

Open Narretz opened 4 months ago

Narretz commented 4 months ago

Would be great if you could specify which types you want in Paths.

For example if you have this type:

type Translations = {
 project: string;
  user: {
    name: {
      firstname: string;
      lastname: string;
    };
  };
};

And you could filter only the strings via Paths, so that the resulting type is this:

"project" | "user.name.firstname" | "user.name.lastname"

For example, if you have a deeply nested object, where each string property is a translation value, and the objects are just used for grouping. I would use Paths to overload the translation function, so I know which translation strings are available.

Or thinking about this differently, the type of would only return the leaf nodes of the tree.

Or can this already be achieved by filtering the strings first? I guess not. You need to store the type information in the type, because you need to traverse the type deeply before you can decide if you need to drop it.

In the meantime, I'm using this: https://www.scalzotto.nl/posts/typescript-paths-and-leaves

Upvote & Fund

Fund with Polar

voxpelli commented 4 months ago

I think there are lots of possible improvements, I eg. opened https://github.com/sindresorhus/type-fest/issues/863 just now, PR:s are welcome

buschtoens commented 4 months ago

Just so it doesn't get lost in the cracks, as the description doesn't further specify it: This issue now also tracks a onlyLeaves: true option as suggested in https://github.com/sindresorhus/type-fest/issues/432#issuecomment-1219428546.

type Post = {
  id: string;
  title: string;
  comments: {
    id: string;
    body: string;
  }[]
}

type fieldType = Path<Post, { onlyLeaves: true }>;

// type fieldType = "id" | "title" | `comments.${number}.id` | `comments.${number}.body`
AdiMarianMutu commented 1 month ago

Any update on the { onlyLeaves: true } option?