Skip to the solution
MediumFrontend9 min read

What do Exclude, Extract, and NonNullable do?

609 views

The problem

Question presented to candidate: "What do Exclude, Extract and NonNullable do? Can you show how Exclude is implemented, and give a case where one of them surprised you?"

What a strong answer should cover:

  • They filter the members of a union: Exclude<T, U> drops members assignable to U, Extract<T, U> keeps only those, NonNullable<T> drops null and undefined
  • Exclude and Extract are one-line distributive conditional types (T extends U ? never : T); members mapped to never vanish from the union
  • Practical uses: narrowing a status union, picking one variant of a discriminated union with Extract<Action, { type: "add" }>, typing a filter that removes empty values, building Omit
  • Limits: they work on unions, not object properties (use Omit for that); Exclude<string, "a"> is still string; U is not checked against T, so typos are silent
  • NonNullable<T> is T & {} since TypeScript 4.8, which lets a narrowed generic value be returned as NonNullable<T>; it is shallow

Code / implementation expected: Optional β€” write MyExclude by hand, or use Extract to pick a union member.

  • exclude
  • extract

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptFiltering string unions, action unions and nullable values
TypeScriptHow they are built, a stricter Exclude and NonNullable as T & {}

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 39 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What are utility types like Partial, Pick, and Omit?

Continue