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.

TypescriptData Integrity

Code

typescriptsnippet
26 lines
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 createdAt

How 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

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.