Skip to content

TypeGuards no longer seem to work #1018

Closed

Description

@NyakoFox
---@class MyClass
---@class MyInheritedClass : MyClass
---@field test fun(): void


---@return TypeGuard<MyInheritedClass>
function typeguard(instance)
    return true
end

---@type MyClass
local instance = {}

if typeguard(instance) then
    instance:test() -- this is MyClass still, this is a warning! Undefined field `test`.

    ---@cast instance MyInheritedClass
    instance:test()
end

Tested on the latest update, and also #1017, both have this issue

Activity

  1. xuhuanzy commented on Apr 6, 2026

    @xuhuanzy
    Member

    This behavior is correct: MyInheritedClass is broader in scope than MyClass, so it cannot be converted.

  2. NyakoFox commented on Apr 6, 2026

    @NyakoFox
    Author

    I am not sure I understand. A very desirable thing to do is:

    ---@param instance VeryGenericClass
    function test(instance)
        if IsSpecializedClass(instance) then
            instance:doSpecializedThing()
        end
    end

    the same way instanceof would be used in Java. If you have a "wide" class, and you want to access more "specialized" behavior on the child, you want to type check, and then run it.

    Is this not a good use of TypeGuard? is there anything else which allows this? It is a very common pattern.

  3. linked a pull request that will close this issueupdate #1017on Apr 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

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