While utilizing Luau’s strict mode to write a short module, I noticed a strange warning relating to function parameters and variadic generics. I recreated the scenario using an example type and function to see if I was doing something wrong, and the warning still appeared. How can I have a “method” that has its parameters matching the parent type? I’ve tried casting the Object variable and that didn’t work either.
I’m using the typechecker beta.
Here’s the error on line 15:
Type Error: Type ‘Example<T…>’ could not be converted into ‘Example’; this is because accessing Method, takes a tail of T... and accessing Method, takes the portion of the type pack starting at index 0 to the endstring, and T... is not exactly string
Here’s the source code:
--!strict
type Example<T...> = {
Method: (T...) -> ();
}
local function CreateExample<T...>(Method: (T...) -> ()): Example<T...>
local self = {}
self.Method = Method
return self
end
local Object: Example<string> = CreateExample(function(a: string)
print(a)
end)
Object.Method("Hello World!")
This is a case that the Luau compiler still can’t handle. I think it’s a tough one to solve, even with type functions, since you’re trying to create a method dynamically. but that’s just my opinion.
What you can do is define Example before using it. You could use overloading for that:
--!strict
type Example<T...> = {
Method: (T...) -> ();
}
type SpecificExample =
Example<string>
& Example<number,string>
-- & ...
--list of all possible Examples
local function CreateExample(Method: any): SpecificExample
local self = {}
self.Method = Method
return self
end
local Object: Example<string> = CreateExample(function(a: string)
print(a)
end)
Object.Method("Hello World!")