Closed
Description
Search Terms
pick, nested, deep
Suggestion
Pick
can only be used to access properties at the top level of an object, it should support paths to get at more deeply nested values.
Use Cases
Typing form inputs from GraphQL fragments
Examples
type Company = {
id: number;
name: string;
address: {
id: number;
street: string;
city: string;
state: string;
};
}
You could then construct a new type as follows:
type FlatCompany = Pick<Company, "id" | "name" | { "addressId": ["address", "id"] }>
Which would yield:
type FlatCompany = {
id: number;
name: string;
addressId: number;
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript codeThis wouldn't change the runtime behavior of existing JavaScript codeThis could be implemented without emitting different JS based on the types of the expressionsThis isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)This feature would agree with the rest of TypeScript's Design Goals.
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
jcalz commentedon Feb 14, 2020
It's virtually impossible that the definition of
Pick
will be modified to do this. See this comment: people rely on the current behavior and performance and implementation ofPick
. You are, however, free to introduce into your own code a type alias, which I'll callHybridDeepPick
, which behaves in any way you'd like:The main problem I see with writing such a type right now is that using tuples to index arbitrarily far down into a type (see #12290) would require more support for circular types than currently exists (#26980). So anything that is built with today's TypeScript would either need to do something unsupported or have an explicit depth limit, and will be ugly either way.
Here's one ugly way which walks down about six or seven levels at most, does nothing good with types containing index signatures or optional/readonly properties, does not prevent you from using bad nested keys (e.g.,
["adress", "streeet"]
will silently fail to index anything) and has not been tested thoroughly enough to go anywhere near a production system:So make of that what you will. Good luck!
Playground link to code
RyanCavanaugh commentedon Feb 19, 2020
👆 Once we ship commonly-used aliases, touching them in any way at all is guaranteed to produce a huge number of confusing breaks, which is why we've tried to stop doing so except when absolutely necessary.
typescript-bot commentedon Feb 22, 2020
This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.