Code Logo

Select Fields with Pick and Omit

Published at25 Jul 2026
TypeScript Generics & Advanced Types Hard 0 views
Like0

Write a TypeScript function that uses Pick to select only the name and age properties from a full User object. Pick creates a new type containing only the specified keys K from T. Omit does the opposite, excluding keys K from T.

The Pick utility type takes a type T and a union of keys K, returning a type with only those properties. It is implemented as a mapped type: { [P in K]: T[P] }. Pick is useful for creating limited views of data, such as public profiles that exclude sensitive fields. Omit is the complement, defined as Pick>.

These utility types are part of TypeScript's mapped types family. They operate entirely at the type level and are erased at runtime. They enable expressing complex type transformations concisely without manual interface duplication.

Time complexity is O(n) for the runtime property access. Space complexity is O(k) for the new object. The Pick type itself has zero runtime overhead as it's a compile-time construct.

Edge cases include picking a single key, omitting all keys (results in empty object type), and ensuring the keys provided to Pick are valid keys of the original type (enforced by the K extends keyof T constraint).

Example Input & Output

Example 1
Input
{"id":3,"name":"Eve","age":35,"email":"e@x.com"}
Output
{"name":"Eve","age":35}
Explanation

Default pick

Example 2
Input
{"id":1,"name":"Alice","age":30,"email":"a@x.com"}
Output
{"name":"Alice","age":30}
Explanation

Pick name and age

Example 3
Input
{"id":4,"name":"X","age":10,"email":"x"}
Output
{"name":"X","age":10}
Explanation

Minimal profile

Example 4
Input
{"id":2,"name":"Bob","age":25,"email":"b@x.com"}
Output
{"name":"Bob","age":25}
Explanation

Another user

Example 5
Input
{"id":5,"name":"Y","age":99,"email":"y"}
Output
{"name":"Y","age":99}
Explanation

Another profile

Algorithm Flow

Recommendation Algorithm Flow for Select Fields with Pick and Omit
Recommendation Algorithm Flow for Select Fields with Pick and Omit

Solution Approach

interface User {
  id: number;
  name: string;
  age: number;
  email: string;
}

type PublicProfile = Pick<User, 'name' | 'age'>;

function solution(user: User): PublicProfile {
  return { name: user.name, age: user.age };
}

Best Answers

typescript - Approach 1
interface User {
  id: number;
  name: string;
  age: number;
  email: string;
}

type PublicProfile = Pick<User, 'name' | 'age'>;

function solution(user: User): PublicProfile {
  return { name: user.name, age: user.age };
}