centau / vide

A reactive Luau library for creating UI.
https://centau.github.io/vide/
MIT License
74 stars 16 forks source link

Fix `switch` return type not resolving correctly #13

Closed littensy closed 1 year ago

littensy commented 1 year ago

Currently, the following erroneous code does not produce a type error:

local source = switch(function() return 1 end) {
    function() return 1 end,
    function() return 1 end,
}

local value = source()

if value then
    value:shouldError()
end

This is caused by differences in behavior between Map<T, ((() -> U)?)> and Map<T, () -> U>. This issue was resolved by replacing the former with the latter.

littensy commented 1 year ago

There's another problem with this, though! While it allows omitting cases, it still displays an error if the component is nullable:

local function show<T>(source: () -> boolean, component: () -> T, fallback: (() -> T)?)
    return switch(source) {
        [true] = component,
        [false] = fallback,
        --        ^^^^^^^^
        -- 🔴 Type '(() -> T)?' could not be converted into '() -> T'
    }
end

I'm not sure how to cover this case as well. If this decision is intentional, feel free to close this! The original issue might be better to report as a Luau bug.

littensy commented 1 year ago

The current behavior is likely the best option. It's definitely worth looking into as a Luau bug, though.