> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript using Declaration

A `using` declaration is a block-scoped variable declaration that guarantees the deterministic execution of a teardown method when the variable's lexical scope is exited. It implements the ECMAScript Explicit Resource Management proposal, binding the lifecycle of an object to the scope in which it is declared.

```typescript theme={"dark"}
// Synchronous declaration
using resource = getResource();

// Asynchronous declaration
await using asyncResource = getAsyncResource();
```

## Protocol Implementation

For an object to be compatible with a `using` declaration, it must implement the `Disposable` interface. This requires defining a method keyed by the well-known symbol `Symbol.dispose`.

```typescript theme={"dark"}
class CustomResource implements Disposable {
    [Symbol.dispose](): void {
        // Synchronous teardown logic
    }
}

function getResource() {
    return new CustomResource();
}
```

For `await using` declarations, the object must implement the `AsyncDisposable` interface, utilizing `Symbol.asyncDispose`. This method must return a `Promise`. Furthermore, `await using` has strict context requirements: it can only be used within an asynchronous context, such as inside an `async` function or at the top level of a module.

```typescript theme={"dark"}
class CustomAsyncResource implements AsyncDisposable {
    async [Symbol.asyncDispose](): Promise<void> {
        // Asynchronous teardown logic
    }
}
```

## Execution Mechanics

**Scope Exit**
The disposal method is invoked implicitly at the end of the containing lexical block. This invocation occurs regardless of whether the block exits normally, via a `return` statement, or due to a thrown exception.

**Null and Undefined Evaluation**
Both `using` and `await using` declarations gracefully handle `null` and `undefined` values. If a resource evaluates to `null` or `undefined`, the disposal phase acts as a no-op. This provides a standard pattern for conditionally acquiring resources without requiring complex branching logic during teardown.

```typescript theme={"dark"}
// If condition is false, disposal is a no-op
using resource = condition ? getResource() : undefined;
```

**Immutability**
Variables declared with `using` or `await using` are implicitly `const`. Any attempt to reassign the variable will result in a compiler error.

**Evaluation Order**
When multiple `using` declarations exist within the same scope, their disposal methods are placed on a stack and executed in reverse order of their declaration (Last-In, First-Out).

```typescript theme={"dark"}
{
    using a = new ResourceA();
    using b = new ResourceB();
    
    // Scope ends. 
    // b[Symbol.dispose]() is called first.
    // a[Symbol.dispose]() is called second.
}
```

**Exception Handling (`SuppressedError`)**
If an exception is thrown during the execution of the block, and the subsequent `[Symbol.dispose]()` call *also* throws an exception, the runtime prevents the original error from being lost. It throws a `SuppressedError`, a built-in `Error` subclass.

The `SuppressedError` exposes two specific properties:

* `error`: The exception thrown during the disposal phase.
* `suppressed`: The original exception thrown during the block's execution.

## Compiler Configuration

To utilize `using` declarations, the TypeScript compiler requires specific target and library configurations in `tsconfig.json`:

```json theme={"dark"}
{
  "compilerOptions": {
    "target": "es2022",
    "lib": ["es2022", "esnext.disposable"]
  }
}
```

If the runtime environment does not natively support `Symbol.dispose` or `Symbol.asyncDispose`, a polyfill for these symbols must be provided globally before the declarations are evaluated.

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor TypeScript Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
