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

# @cast

> Narrow or change a variable's type at a specific point in the code.

## Overview

`@cast` tells GLuaLS to treat a variable as a specific type from that line onward. Use it to narrow unions, assert non-nil values, or correct inference in dynamic code.

***

## Syntax

```lua theme={null}
---@cast varName TypeExpression
---@cast varName +TypeExpression   -- add type to union
---@cast varName -TypeExpression   -- remove type from union
```

***

## Basic type assertion

```lua theme={null}
---@type string | number
local value = getValue()

if type(value) == "string" then
    ---@cast value string
    print("Length:", #value)  -- ✅ narrowed to string
end
```

***

## Non-nil assertion

```lua theme={null}
---@type Player | nil
local ply = findPlayer(id)

---@cast ply Player  -- assert not nil (removes nil from the union)
ply:ChatPrint("Found!")  -- ✅ no need-check-nil warning
```

***

## Casting to a more specific type

```lua theme={null}
---@type Entity
local ent = ents.GetByIndex(1)

---@cast ent Player  -- assert that ent is actually a Player
ent:GetFriends()     -- ✅ Player method available
```

***

## Adding to a union

```lua theme={null}
---@type string
local val = "hello"

---@cast val +number  -- val is now string | number
```

***

## Removing from a union

```lua theme={null}
---@type string | number | nil
local val = getVal()

---@cast val -nil  -- removes nil, val is now string | number
```

***

## Inline table casting

```lua theme={null}
---@type table
local data = getData()

---@cast data { id: number, name: string }
print(data.id)    -- ✅
print(data.name)  -- ✅
```

***

## When to use @cast vs @type

* Use `@type` on new variable declarations when GLuaLS cannot infer the type
* Use `@cast` after a variable already exists to narrow or correct its type without redeclaring it
