Skip to content

Table type annotations #3295

Description

@Dan-Crane

Hello everyone.

I've defined a field as table<MyStates, BaseState>, but the analyzer doesn't complain when I assign a table with a completely different structure to it.

---@class BaseState
local BaseState = {}

---@enum MyStates
local States = {
    GAME = 1,
    GAME_OVER = 2,
}

---@class MyStateMachine
---@field private _states table<MyStates, BaseState>
local MyStateMachine = {}
MyStateMachine.__index = MyStateMachine

---@param states table<MyStates, BaseState>
function MyStateMachine:setStates(states)
    self._states = states
end

function tmp()
    -- Assigning a table with a different annotation directly. The analyzer doesn't complain.
    MyStateMachine._states = {
        ['kek'] = 69
    }
    -- Passing a table with a different annotation to a method. The analyzer doesn't complain.
    MyStateMachine:setStates({
        ['kek'] = 69,
    })
    -- The analyzer correctly complains about a number assignment.
    -- MyStateMachine._states = 69
    -- The analyzer correctly complains about passing a number.
    -- MyStateMachine:setStates(2)
end

As you can see, the type checker only seems to validate that the value is a table, but doesn't validate the internal key and value types for table<MyStates, BaseState>. Is this the expected behavior, or am I missing something? Is there a way to enforce stricter type checking for the contents of generic tables?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions