Type checker disallows writing to fields after refining optional type

The following code should have no type errors because in both union options we have the same fields. However, the type checker doesn’t like it, and for both lines gives the error Expected type table, got 'A1 | A2' instead

type A1 = {
	B: number?;
	C: number;
}
type A2 = {
	B: number?;
	C: number;
}
type A = A1 | A2
local A: A = nil
if not A.B then
	-- These two lines have type errors.
	A.B = 1
	A.C = 2
end

This is just an acknowledgment announcement!

We’ve filed a ticket into our internal database for this issue, and we will update you when we have further information!

Thanks for the report!

1 Like

Hey there, and thank you for the report! This issue has been partially improved in the New Type Solver in that our treatment of unions and refinements is broadly better, meaning that A.C will be allowed on A without any issue (and indeed without refinement too since it’s coming amongst all components of the union). The refinement does also apply to the type of A.B to learn that it’s nil within that branch, but a separate bug in the New Type Solver means that A.B ends up refined to nil preventing you from writing anything that isn’t nil into the field. In a literal sense, things have improved, but a separate bug (already recorded in our backlog) is preventing the assignment for A.B from happening. On the other hand though, you can do the positive refinement e.g. if A.B then and be able to use that B property as a number (but likewise, the same new refinement bug will prevent you from assigning nil to it despite the fact that the annotation has it being optional). We’re hard at work trying to fix these known issues in the New Type Solver!

1 Like

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