Question presented to candidate: "How do you type async functions and Promises in TypeScript? Walk me through return types, errors, and running several promises at once โ and tell me which async bugs the compiler will not catch."
What a strong answer should cover:
- An async function always returns
Promise<T>: annotatePromise<User>(annotatingUseris error TS1064),Promise<void>when nothing useful is returned; plain returned values are wrapped new Promise<T>(...)needs its type argument or the value isunknown; callback types say() => Promise<T>;AwaitedandReturnTypederive types from existing async functions- Errors are untyped:
Promise<T>has no error parameter, acatch (err)variable isunknownunderstrict(TypeScript 4.4+), but.catchandallSettledreasons areany - Concurrency:
Promise.allon an array literal gives a typed tuple,allSettledresults narrow onstatus,racewith aPromise<never>timeout keeps the result type - Bugs tsc does not flag: async callbacks passed to
forEach, floating promises,returnwithoutawaitinsidetryโ lint rules likeno-floating-promisescover some of them
Clarifying questions expected:
- Should independent calls run in parallel or one after another?
- Is
strict(oruseUnknownInCatchVariables) on, and is type-aware linting part of the toolchain?
Code / implementation expected: Yes โ a typed async function with error handling, and a Promise.all or allSettled call.