luau
luau copied to clipboard
Tables inserted with `table.insert` are not inferred to union-valued table
--!strict
local value: {{string | number}} = {}
table.insert(value, {
"",
1
})
TypeError: Type 'number' could not be converted into 'string'
I can still reproduce this.
It seems to be more general than table.insert - anecdotally, I've seen this pop up in Fusion code when passing arrays of values which are not exactly the same type.
My read on this issue is that, when constructing an array {value1, value2, value3}, Luau implicitly assumes the type {T} and expects value1: T, value2: T, value3: T. It decides that T = typeof(value1), which then requires that value2: typeof(value1) and value3: typeof(value1).
In the above code snippet, this does not hold true, so it fails.
My belief is that this is done at the table literal level, and probably isn't special to table.insert. I think that the type of the table literal is too specific, and the correct solution would be to loosen up the type expectations and prefer to infer the types from surrounding code (e.g. take the type of the table from the definition of the function it's being passed into).
That's my read as someone who isn't versed in the academia, anyway.
By the way, for anyone else with this issue, the 'solution' is to cast the first value to the type you want, or just any if all you care about is making the error go away.
Actually, same issue as #664 it seems. This might be a dupe.