Skip to content

Type Guards and Validation ​

Runtime Type Checking ​

Utility functions for runtime type checking:

lua
-- Check if value is a valid inventory item
local function isInventoryItem(value: any): boolean
    return typeof(value) == "table"
        and typeof(value.Id) == "string"
        and typeof(value.Name) == "string"
        and typeof(value.Rarity) == "string"
        and typeof(value.Level) == "number"
end

-- Check if change info is enhanced
local function isChangeInfo(value: any): boolean
    return typeof(value) == "table"
        and typeof(value.action) == "string"
        and typeof(value.path) == "table"
end

-- Type-safe array access
local function getInventoryItem(index: number): InventoryItem?
    if not PlayerState.IsReady() then
        return nil
    end

    local inventory = PlayerState.GetPath("Inventory")

    if typeof(inventory) ~= "table" or not inventory[index] then
        return nil
    end

    local item = inventory[index]
    return isInventoryItem(item) and item or nil
end

-- Validate batch operations
local function validateBatchOperations(operations: {BatchOperation}): boolean
    for _, operation in operations do
        if typeof(operation.path) ~= "string" or operation.value == nil then
            return false
        end

        -- Check for leaderstats paths
        if operation.path == "leaderstats" or string.sub(operation.path, 1, 12) == "leaderstats." then
            warn(`Invalid batch operation: cannot modify leaderstats path {operation.path}`)
            return false
        end
    end

    return true
end

PlayerState - High-Performance Roblox Data Management