Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Narretz opened this issue Apr 10, 2024 · 2 comments
Open

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

Narretz opened this issue Apr 10, 2024 · 2 comments

Comments

@Narretz
Copy link

Narretz commented Apr 10, 2024

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

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@Narretz Narretz changed the title Exclude / Pick type in Paths Exclude / Pick type in Paths / only add leaves Apr 10, 2024
@Narretz Narretz changed the title Exclude / Pick type in Paths / only add leaves Exclude / Pick type in Paths / only add leaf nodes Apr 10, 2024
@voxpelli
Copy link
Collaborator

I think there are lots of possible improvements, I eg. opened #863 just now, PR:s are welcome

@buschtoens
Copy link
Contributor

buschtoens commented Apr 17, 2024

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 #432 (comment).

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`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants