DeepPick Extracts Nested Property Types
Build DeepPick from recursive tuple paths so nested types survive, and intersect multiple paths into one precise shape.
Code
type DeepPick<T, Path extends readonly PropertyKey[]> = Path extends readonly [
infer Head extends keyof T,
...infer Rest extends readonly PropertyKey[],
]
? Rest extends readonly []
? Pick<T, Head>
: { [K in Head]: DeepPick<T[Head], Rest> }
: never;
interface Payload {
user: {
id: string;
profile: { name: string; email: string };
};
meta: { version: number };
}
type NameOnly = DeepPick<Payload, ['user', 'profile', 'name']>;
type MetaOnly = DeepPick<Payload, ['meta', 'version']>;
type Picked = NameOnly & MetaOnly;
const picked: Picked = {
user: { profile: { name: 'ada' } },
meta: { version: 2 },
};
console.log(picked.user.profile.name, picked.meta.version);
console.log('top keys:', Object.keys(picked).join(','));
// 路径不存在时无法通过编译
// const broken: DeepPick<Payload, ['user', 'missing']> = {};Output
Captured from a sandboxed run of this snippet in the build pipeline.
ada 2
top keys: user,metaWhat to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Running the file prints labeled results such as top keys: — each operation’s effect is visible in the output.
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library.
Report a problem with this exampleOpens a pre-filled issue on GitHub.