Type error with function table parameters

Minimal reproduction code:

--!strict
type Object<T> = {
	type: T
}

type Thing = {
	[string | Object<any>]: any
}

function ret<T>(t: T) 
	return t
end

local _: Thing = ret {
	[{ type = "hello" } :: Object<"hello">] = 2,
	[{ type = "foo" } :: Object<"foo">] = "hello!",  -- type error, but there shouldn't be
	hello = workspace
}

There are two TypeErrors here:

TypeError: Type
    'Object<"foo">'
could not be converted into
    'Object<"hello">'
caused by:
  Property 'type' is not compatible.
Type '"foo"' could not be converted into '"hello"' in an invariant context
TypeError: Type 'string' could not be converted into 'number'

How do I fix this?

Update: the same thing happens if Thing is simply:

type Thing = {[any]: any}

I have a feeling this is just one of those challenges that you get a prize for if you solve it…

It appears so. I keep running into many related type checker errors because Luau infers the strictest type based on the first item in the table, so I have to add a load of ugly type casts everywhere :frowning:

I’ll just mark this as solved.

Ah, this is solved in a future version of Luau with DebugLuauDeferredConstraintResolution. Unfortunately, my LSP server does not support it.

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