As a Roblox developer, it is currently not possible to dynamically change the return type of a function from within the function itself. While generic typing can be used for cases where a function’s return type changes to match the type of an argument passed to that function, as shown in this barebone example:
local function generic<T>(value: T): T
return value
end
print(generic(1234)) -- generic(value: number): number
print(generic("Hello!")) -- generic(value: string): string
a method to change the return type of a function from within itself isn’t currently implemented, but would allow ideal compatibility with strict type-checking for cases such as the example shown below for a function that creates and sets the properties of an Instance using a dictionary:
local function create(className: string, parent: Instance?, properties: {[string]: any}?)
local instance = Instance.new(className)
if properties then
for property, value in properties do
if property == "Parent" then continue end
instance[property] = value
end
end
instance.Parent = parent
return instance
end
local part: Part = create(
"Part",
workspace,
{
Color = Color3.new(1, 0.5, 0),
Size = Vector3.one * 4,
Anchored = true
}
)
If this issue is addressed, it would improve my development experience because it would be much more convenient if a method such as the one shown in this example would be possible to use:
local function create(className: string, parent: Instance?, properties: {[string]: any}?): dynamic
local instance = Instance.new(className)
dynamic:: typeof(instance)
if properties then
for property, value in properties do
if property == "Parent" then continue end
instance[property] = value
end
end
instance.Parent = parent
return instance
end
local part = create(
"Part",
workspace,
{
Color = Color3.new(1, 0.5, 0),
Size = Vector3.one * 4,
Anchored = true
}
)