---@param value anyfunction processValue(value) if type(value) == "string" then ---@cast value string print("String length:", #value) -- value is now confirmed as string type end if type(value) == "table" and value.id then ---@cast value {id: number, name?: string} print("ID:", value.id) -- value now has id field endend
---@type tablelocal data = parseJSON(jsonString)-- Cast to specific structure---@cast data {users: {id: number, name: string}[]}for _, user in ipairs(data.users) do print("User:", user.name, "ID:", user.id)end
---@param input string | number | booleanfunction handleInput(input) if type(input) == "string" and input:match("^%d+$") then ---@cast input string -- Confirm it's string type local num = tonumber(input) ---@cast num number -- tonumber result confirmed as number print("Number:", num) endend
-- Add multiple types---@type stringlocal value = "initial"---@cast value +number, +boolean -- Add number and boolean types-- value is now: string | number | boolean-- Remove multiple types---@type string | number | boolean | nillocal multiValue = getMultiValue()---@cast multiValue -boolean, -nil -- Remove boolean and nil types-- multiValue is now: string | number
---@param data anyfunction processData(data) if validate(data) then ---@cast data {id: number, name: string, email: string} -- Now safely access typed fields local userId = data.id local userName = data.name endend
---@type string?local optionalValue = getOptional()if optionalValue ~= nil then ---@cast optionalValue string -- Remove nil from type -- Safe to use as string now print(optionalValue:upper())end
Type casts do not perform runtime type conversion. They only inform the analyzer about the type. Always ensure your runtime checks match your casts.
Use @cast after validation logic to help the analyzer understand type narrowing from your runtime checks.