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 toU,Extract<T, U>keeps only those,NonNullable<T>dropsnullandundefined ExcludeandExtractare one-line distributive conditional types (T extends U ? never : T); members mapped tonevervanish 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, buildingOmit - Limits: they work on unions, not object properties (use
Omitfor that);Exclude<string, "a">is stillstring;Uis not checked againstT, so typos are silent NonNullable<T>isT & {}since TypeScript 4.8, which lets a narrowed generic value be returned asNonNullable<T>; it is shallow
Code / implementation expected: Optional β write MyExclude by hand, or use Extract to pick a union member.