Skip to the solution
MediumFrontend11 min read

How does using / await using with Symbol.dispose work in TypeScript 5.2+?

1.2k views

The problem

Question presented to candidate: "TypeScript 5.2 added using and await using. What do they do, how does an object opt in with Symbol.dispose, in what order does cleanup run, and what do you need in your config and runtime to use them today?"

What a strong answer should cover:

  • using x = expr declares a const-like, block-scoped binding whose [Symbol.dispose]() is called when the block exits, at the end of the block, on return and on throw; several bindings dispose in reverse order (last in, first out)
  • The types: Disposable ([Symbol.dispose](): void) and AsyncDisposable ([Symbol.asyncDispose](): PromiseLike<void>); the initializer must be one of those or null/undefined (TS2850), and await using only works in async code (TS2852)
  • await using awaits Symbol.asyncDispose (falling back to Symbol.dispose) before leaving the block
  • Errors: a body error is rethrown after cleanup; if cleanup also throws, both are wrapped in a SuppressedError (error = the newer, suppressed = the earlier)
  • Setup: lib must include esnext or esnext.disposable; for older targets TypeScript emits helper code (__addDisposableResource, __disposeResources); runtimes without the built-ins need at least Symbol.dispose / Symbol.asyncDispose polyfills

Code / implementation expected: Yes β€” a small resource class with [Symbol.dispose], two using bindings, and the order of the log lines.

  • using
  • resource-management

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

11 min read Β· 11 sections

Run the code

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

TypeScriptusing: reverse-order disposal on return and throw
TypeScriptawait using, mixed disposables and SuppressedError

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 14 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 is the definite assignment assertion (!)?

Continue