> For the complete documentation index, see [llms.txt](https://gofast.disasm.dev/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gofast.disasm.dev/type-assertions.md).

# Type Assertions

In go-fAST, understanding the type of AST node you're working with is fundamental to writing effective visitors and transformations. Since the library is written in Go, it leverages Go's type system and interfaces to represent different nodes. To inspect and work with a specific node type, you'll use Go's built-in type assertions.

This guide explains how to:

* Identify the type of an `Expr` or `Stmt`
* Use type assertions for transformation and analysis
* Understand the common AST node types you'll encounter

***

### 🧠 What Is a Type Assertion?

In Go, if you have an interface (like `Expr` or `Stmt`), and you want to know whether it holds a specific concrete type, you use a type assertion:

```go
if ident, ok := expr.Expr.(*ast.Identifier); ok {
    fmt.Println("This is an identifier with name:", ident.Name)
}
```

If `expr.Expr` is a `*ast.Identifier`, the cast succeeds and `ok` is `true`. If not, `ok` will be `false`, and the cast fails gracefully.

***

### ✅ Checking for Expression Types

All expressions in go-fAST implement the `ast.Expr` interface. To check for specific types, you usually work through `*ast.Expression` wrappers:

```go
type ExampleVisitor struct {
    ast.NoopVisitor
}

func (v *ExampleVisitor) VisitExpression(n *ast.Expression) {
    switch e := n.Expr.(type) {
    case *ast.CallExpression:
        fmt.Println("Found a function call:", e.Callee)
    case *ast.SequenceExpression:
        fmt.Println("This is a sequence of expressions.")
    case *ast.AssignExpression:
        fmt.Println("Assignment to:", e.Left)
    default:
        fmt.Println("Some other expression")
    }
}
```

Common expression types:

* `*ast.CallExpression`
* `*ast.SequenceExpression`
* `*ast.AssignExpression`
* `*ast.Identifier`
* `*ast.MemberExpression`
* `*ast.NumberLiteral`, `*ast.StringLiteral`, `*ast.BooleanLiteral`

***

### 📚 Full List of Statement Types (`Stmt`)

All statement nodes implement the `Stmt` interface. You can check for these types in visitors like `VisitStatement`, `VisitStatements`, or any higher-level node.

| Node Type              | Purpose                       |
| ---------------------- | ----------------------------- |
| `*BadStatement`        | Invalid syntax fragment       |
| `*BlockStatement`      | `{ ... }` code blocks         |
| `*BreakStatement`      | `break`                       |
| `*ContinueStatement`   | `continue`                    |
| `*CaseStatement`       | `case` clause inside `switch` |
| `*CatchStatement`      | `catch` block inside `try`    |
| `*DebuggerStatement`   | `debugger;`                   |
| `*DoWhileStatement`    | `do { ... } while (...)`      |
| `*EmptyStatement`      | `;` (no-op statement)         |
| `*ExpressionStatement` | Expression as a statement     |
| `*ForStatement`        | `for (;;)` loop               |
| `*ForInStatement`      | `for (x in y)`                |
| `*ForOfStatement`      | `for (x of y)`                |
| `*IfStatement`         | `if (...) ... else ...`       |
| `*LabelledStatement`   | `label: ...`                  |
| `*ReturnStatement`     | `return ...;`                 |
| `*SwitchStatement`     | `switch (...) { ... }`        |
| `*ThrowStatement`      | `throw ...;`                  |
| `*TryStatement`        | `try { ... } catch { ... }`   |
| `*WhileStatement`      | `while (...) { ... }`         |
| `*WithStatement`       | `with (...) { ... }`          |

***

### 🧠 Expression Types (`Expr`)

All expressions implement the `Expr` interface. These are the building blocks of values, calls, operations, etc.

| Node Type                | Description                            |
| ------------------------ | -------------------------------------- |
| `*ArrayLiteral`          | `[1, 2, 3]`                            |
| `*ArrowFunctionLiteral`  | `(x) => x * 2`                         |
| `*AssignExpression`      | `a = b` or `a += b`                    |
| `*AwaitExpression`       | `await x`                              |
| `*BinaryExpression`      | `a + b`, `a === b`                     |
| `*CallExpression`        | `f(x)`                                 |
| `*ConditionalExpression` | `a ? b : c`                            |
| `*InvalidExpression`     | Malformed expression                   |
| `*MemberExpression`      | `obj.prop` or `obj["prop"]`            |
| `*MetaProperty`          | `new.target`, `import.meta`            |
| `*NewExpression`         | `new Foo()`                            |
| `*ObjectLiteral`         | `{ a: 1, b: 2 }`                       |
| `*PrivateDotExpression`  | `this.#privateField`                   |
| `*PrivateIdentifier`     | `#field`                               |
| `*SequenceExpression`    | `(a, b, c)`                            |
| `*SpreadElement`         | `...rest` in arrays or objects         |
| `*SuperExpression`       | `super.method()`                       |
| `*TemplateLiteral`       | `` `hello ${name}` ``                  |
| `*ThisExpression`        | `this`                                 |
| `*UnaryExpression`       | `!a`, `typeof x`, `-y`                 |
| `*UpdateExpression`      | `++x`, `x--`                           |
| `*YieldExpression`       | `yield x`                              |
| `*OptionalChain`         | `obj?.prop`                            |
| `*Optional`              | Wrapper for optional expressions       |
| `*ArrayPattern`          | `[a, b] = [1, 2]`                      |
| `*ObjectPattern`         | `{a, b} = obj`                         |
| `*VariableDeclarator`    | `var x = 1` (used inside declarations) |

### ✅ Checking for Statement Types

Statements implement the `ast.Stmt` interface and are accessed via `*ast.Statement` nodes:

```go
type ExampleVisitor struct {
    ast.NoopVisitor
}

func (v *ExampleVisitor) VisitStatement(n *ast.Statement) {
    switch s := n.Stmt.(type) {
    case *ast.ReturnStatement:
        fmt.Println("Returning value:", s.Argument)
    case *ast.ExpressionStatement:
        fmt.Println("Expression statement")
    case *ast.IfStatement:
        fmt.Println("Conditional if detected")
    default:
        fmt.Println("Unhandled statement type")
    }
}
```

Common statement types:

* `*ast.ReturnStatement`
* `*ast.ExpressionStatement`
* `*ast.BlockStatement`
* `*ast.IfStatement`
* `*ast.ForStatement`, `*ast.WhileStatement`
* `*ast.VariableDeclaration`

***

### 🧩 Advanced Usage: Visitor Filtering

You can use assertions in your custom visitors to conditionally apply logic:

<pre class="language-go"><code class="lang-go">type ExampleVisitor struct {
    ast.NoopVisitor
}

<strong>func (v *ExampleVisitor) VisitExpression(n *ast.Expression) {
</strong>    if call, ok := n.Expr.(*ast.CallExpression); ok {
        if ident, ok := call.Callee.Expr.(*ast.Identifier); ok &#x26;&#x26; ident.Name == "alert" {
            fmt.Println("Found an alert() call!")
        }
    }
}
</code></pre>

***

### 📚 Pro Tip: Create Helpers

You can abstract repeated checks into helpers:

```go
func isConsoleLog(expr *ast.Expression) bool {
    call, ok := expr.Expr.(*ast.CallExpression)
    if !ok {
        return false
    }

    if mem, ok := call.Callee.Expr.(*ast.MemberExpression); ok {
        if obj, ok := mem.Object.Expr.(*ast.Identifier); ok && obj.Name == "console" {
            if prop, ok := mem.Property.Prop.(*ast.Identifier); ok && prop.Name == "log" {
                return true
            }
        }
    }
    return false
}
```

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://gofast.disasm.dev/type-assertions.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
