type-fest
type-fest copied to clipboard
Exclude / Pick type in Paths / only add leaf nodes
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.
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
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`