Expected type table, got ‘nil’ instead

Hi fellow developers,

Can you help check this issue? I think it’s a bug, but I don’t understand how types work in Luau so I can’t be sure.

A common use case for me is to declare a variable and state the type as part of the declaration. I expect this will help autocomplete find the methods and properties when I write the code.

However, when I create an instance using the example code, script analysis does not recognize the type. It returns “Type Error: (5,2) Expected type table, got ‘nil’ instead”

This first happened on Friday 4th august.

Minimal reproduction steps:

Create a blank baseplate project and add this code in a new script

local event:RemoteEvent

if not event then
	event=Instance.new("RemoteEvent")::RemoteEvent
	event.Name="Name"
end

event=Instance.new("RemoteEvent")
event.Name="Name"

if not event then
	event=Instance.new("RemoteEvent")
	event.Name="Name"
end

local event2
if not event2 then
	event2=Instance.new("RemoteEvent")
	event2.Name="Name"
end

This happens regardless of whether plugins are enabled or disabled.

It happens with a “Part” instead of “RemoteEvent”.

It also happens when I cast the result of Instance.new() to the expected type. (Screenshot)

It does not happen when the if-then is not present. (Screenshot)

It does not happen when I omit the type declaration from the local variable declaration. (Screenshot)

There are no run-time errors when executing the code.

I do have a workaround, as I can use this instead.

if event~=nil then

But I don’t get why the type checker would consider something cast to RemoteEvent to be of type nil, or something returned from Instance.new().

What do you think: Is this a bug in the type checker, or is “not event” invalid Luau code, which just happens to work?

1 Like

It’s weird, I tried myself and I didn’t see anything in the output. Remove the ::RemoEvent thing and check.