I don't understand the type system

Here is my code:

local loss:{string} = info.Loss
for _,attrName in loss do
	if attrName == "Stones" then
		for i = 100,0,-1 do
			if player:GetAttribute("Stone"..i) then
				player:SetAttribute("Stone"..i,0)
			end
		end
	elseif attrName:sub(1,8) == "Upgrades" then
				
	else
		player:SetAttribute(attrName,0)
	end
end

There’s a warning by this line:

elseif attrName:sub(1,8) == "Upgrades" then

Basically, it’s because :sub expects a string, but attrName is type ‘string & ~= “Stones”’
I have 3 questions:

  • I know that the line only runs if attrName isn’t “Stones”, but what does that have to do with the type? I didn’t even know that it could be “~= a certain value” until right now.
  • Why does it think that it’s NOT a string just because it isn’t “Stones”?
  • I’m not using !strict so why does it care what type it is?

Sorry if the answer is obvious but I don’t know that much about types

Notice how you have this statement before you check Upgrades:

The type system is just being “cautious” in a way. It’s assigning the type string & ~= "Stones" to let you know that attrName is definitely not the literal string “Stones”.

It’s not that it doesn’t think it’s a string, it’s inferring that attrName is a string AND NOT “Stones”.

Now it should just be Upgrades / string since that’s the only other option in your table I assume but I’m not sure if LuaU supports type narrowing.

Now that I don’t know


Now to fix this, it’s pretty easy: just type cast (pretty sure you can do this):

for _,attrName:: string in loss do

If it thinks that attrName is a string, why doesn’t :sub work on it?

Because it’s inferring that it’s a string and also not “Stones”.

It’s a union type meaning it’s both at once.

So it’s unable to use any string methods and if “Stones” was instead a table, you wouldn’t be able to use any table methods either (hopefully this made sense).

I’m still kind of confused on why it assigns a whole new type to it just because it’s not a specific value (“Stones”), especially when I’m not using !strict

Yeah I’m not sure entirely sure either. All I can assume is that it’s being precautious.