Question presented to candidate:
"What does the infer keyword do in TypeScript? Show me how you would use it to pull a type out of another type, like the return type of a function."
What a strong answer should cover:
infer Xdeclares a new type variable inside theextendsclause of a conditional type; TypeScript fills it in by matching the checked type against the pattern, andXis usable in the true branch- If the pattern does not match, the false branch is taken;
inferis only legal in theextendsclause (error TS1338 elsewhere) - It can sit in any position: return type, parameters, array element, tuple head or rest, a generic argument like
Promise<infer V>, or a hole in a template literal type - Built-ins such as
ReturnType,ParametersandInstanceTypeare written with it (added with conditional types in TypeScript 2.8) - Finer rules: one name in several covariant spots gives a union, in parameter spots an intersection;
infer X extends C(TypeScript 4.7) constrains the match; overloaded functions infer from the last signature
Code / implementation expected: Yes β write a MyReturnType<F> or ElementOf<T> with infer, and explain the false branch.