PickByValue Keeps Fields Matching A Value Type
A mapped as-clause filters interface fields by value type, so PickByValue yields a record with only the string, Date, or array fields.
Code
interface User {
id: string;
name: string;
age: number;
createdAt: Date;
tags: string[];
}
// PickByValue keeps only the fields whose value type extends V
type PickByValue<T, V> = { [K in keyof T as T[K] extends V ? K : never]: T[K] };
type StringFields = PickByValue<User, string>; // id, name
type DateFields = PickByValue<User, Date>; // createdAt
type ArrayFields = PickByValue<User, string[]>; // tags
const strings: StringFields = { id: 'u1', name: 'Ada' };
const dates: DateFields = { createdAt: new Date('2026-01-01') };
const arrays: ArrayFields = { tags: ['core', 'edge'] };
// keyof over the picked type names the matching fields without their values
type DateKeys = keyof PickByValue<User, Date>;
const key: DateKeys = 'createdAt';
console.log(strings.id, strings.name);
console.log(dates.createdAt.toISOString().slice(0, 10));
console.log(arrays.tags.join(','), key);Output
Captured from a sandboxed run of this snippet in the build pipeline.
u1 Ada
2026-01-01
core,edge createdAtHow the snippet works
The top-level object literal pins id, name as plain values — no derivation, no imports behind them.
Caveats
- The runtime is the only requirement — no packages, no install.
Statements that matter
type PickByValue<T, V> = { [K in keyof T as T[K] extends V ? K : never]: T[K] };
type DateKeys = keyof PickByValue<User, Date>;
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.