Luau error indexing into result of ternary operator returning a table from either result

I noticed somewhere in my code that the result of a ternary operator triggered an odd error later on when indexing into it.

Trying to minimize the repro case to the minimum size possible produces this:

--!strict
local test = if true then {} else {}
local lest2 = test[1] -- The error is Expected type table, got '{ } | { }' instead.

Note that if you specify test as being of type {} on the declaration line, then Luau successfully resolves this. This is an easy workaround.

--!strict
local test: {} = if true then {} else {}
local lest2 = test[1] -- no error here

This also does not reproduce with custom named types. If you have a function returning a named type, then the resolver can work out, for example:

--!strict
type foo = {}
function a(): foo return {} end
function b(): foo return {} end
local test = if true then a() else b()
local lest2 = test[1] -- no error here. type of test is '{| |}'

Using foo = {number} resolves to {number}, etc.

This fails with non-named types returned from functions.

--!strict
function a(): {} return {} end
function b(): {} return {} end
local test = if true then a() else b()
local lest2 = test[1] -- The error is Expected type table, got '{| |} | {| |}' instead.

Expected behavior

Luau should understand that result of the ternary operator is still indexable and not show an error or warning here. Note that the # (table count operator) works just fine on these mixed types without producing an error.

A private message is associated with this bug report

3 Likes

Hi there, thanks for reporting this issue!

Longer-term, we’d like to potentially improve the normalization of types to prevent these sorts of types from existing altogether (i.e. {} | {} should really just be normalized to {} in the first place), but we can implement a shorter-term improvement to eliminate the spurious error when indexing on unions or intersections of tables generally. Keep an eye out for it in an upcoming release!

4 Likes

Hey there, just wanted to circle back to say that the fix has been released to users and the corresponding flag flipped on. So, you shouldn’t see this flavor of spurious errors when indexing unions and intersections of table types! Thanks for the report, and please feel free to open a new issue if you find other bugs with the type system!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.