tezvyn:

Explain Pick versus Omit with User examples

AI-drafted, machine-checkedSource: typescriptlang.orgbeginner
WHAT IT TESTS

Explicit selection versus type subtraction.

ANSWER OUTLINE

Pick keeps listed keys; Omit drops them. Show User with id, name, email; derive Pick<User,"name"|"email"> and Omit<User,"id">.

RED FLAG

Confusing them or calling one strictly safer.

WHAT THIS TESTS: This question checks if you understand structural typing and key mapping in TypeScript. Specifically, it probes whether you know that Pick is an explicit allowlist of keys while Omit is a denylist, and whether you can articulate when each communicates intent more clearly. It also surfaces whether you grasp that K in Pick must extend keyof T, whereas Omit can accept string number or symbol or a union that TypeScript will filter.

A GOOD ANSWER COVERS: Four things in order. First, the definition: Pick T K constructs a new type by selecting only the properties of T whose keys are in the union K. Omit T K constructs a new type by taking all properties of T and removing those whose keys are in K. Second, a concrete User example starting from interface User with id string, name string, and email string. Third, the derived types: type UserContactInfo equals Pick User, "name" union "email" produces name and email, while type UserWithoutId equals Omit User, "id" produces name and email. Fourth, the intent distinction: Pick says these specific fields matter now, while Omit says this specific field should be excluded, often for a DTO or public view model.

COMMON WRONG ANSWERS: Saying Pick and Omit are opposites in all cases without noting they can produce identical shapes. Claiming one is safer or more performant than the other. Forgetting that Pick requires K extends keyof T, which means passing a nonexistent key is a compile error, whereas Omit silently ignores keys that do not exist on T. Providing examples that do not use the exact User interface requested.

LIKELY FOLLOW-UPS: How would you implement Pick or Omit from scratch using mapped types? What happens if you pass a key to Omit that does not exist on the base type? When would you prefer Pick over Omit in a large codebase? How do these utilities interact with union types or optional properties?

ONE CONCRETE EXAMPLE: Start with interface User containing id string, name string, and email string. For Pick, write type UserContact equals Pick User, "name" union "email" and instantiate const contact with name Ada and email ada at example dot com. For Omit, write type PublicUser equals Omit User, "id" and instantiate const publicUser with name Ada and email ada at example dot com. Mention that both resulting types contain name and email, but the Pick version explicitly selects them while the Omit version explicitly removes id.

Read the original → typescriptlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.