Skip to main content

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

---@cast varName TypeExpression
---@cast varName +TypeExpression   -- add type to union
---@cast varName -TypeExpression   -- remove type from union

Basic type assertion

---@type string | number
local value = getValue()

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

Non-nil assertion

---@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

---@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

---@type string
local val = "hello"

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

Removing from a union

---@type string | number | nil
local val = getVal()

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

Inline table casting

---@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