luau-lang / luau

A fast, small, safe, gradually typed embeddable scripting language derived from Lua
https://luau.org
MIT License
3.93k stars 370 forks source link

Type 'ConnectionObject?' could not be converted into 'ConnectionObject?' #918

Open RealEthanPlayzDev opened 1 year ago

RealEthanPlayzDev commented 1 year ago

Reproduction code

--!strict

type Function = (...any) -> (...any)
type ConnectionObject = {
    Disconnect: () -> ()
}
type SignalObject = {
    Connect: (self: SignalObject, f: Function) -> (ConnectionObject?),
}
type SignalInterface = {
    Signal: SignalObject
}

function Once(self: SignalInterface)
    local Connection; Connection = self.Signal:Connect(function(... : any)
        if Connection and typeof(Connection["Disconnect"]) == "function" then
            Connection:Disconnect()
        end
    end)
    return
end

image

Can be reproduced on

vegorov-rbx commented 1 year ago

This happens when error was generated at a point where type wasn't known to be ConnectionObject?.

I would suggest adding a type annotation to avoid the error:

type Function = (...any) -> (...any)
type ConnectionObject = {
    Disconnect: (self: ConnectionObject) -> ()
}
type SignalObject = {
    Connect: (self: SignalObject, f: Function) -> (ConnectionObject?),
}
type SignalInterface = {
    Signal: SignalObject
}

function Once(self: SignalInterface)
    local Connection: ConnectionObject?; Connection = self.Signal:Connect(function(... : any)
        if Connection and typeof(Connection["Disconnect"]) == "function" then
            Connection:Disconnect()
        end
    end)
    return
end
RealEthanPlayzDev commented 1 year ago

I would suggest adding a type annotation to avoid the error:

From my understanding, wouldn't the SignalObject's Connect: (self: SignalObject, f: Function) -> (ConnectionObject?) already handle this? (as in the return being a ConnectionObject?)