In many languages such as C++ or Java, it is possible to pass type arguments such as:
SomeFunction<MyType>()
This allows for further abstraction and would be a fantastic extension to the Luau language. Currently it is possible to do this via passing a value which holds the type you are interested in. This is okay but is ugly to work with, and also slower and less intuitive.
This is a very over-simplified example, in reality these would be massive objects such as Items which contain functions and various other things.
type parentType = {
id: string,
}
type type1 = {
x: number?,
} & parentType
type type2 = {
y: number?,
} & parentType
local cache: {[string]: parentType} = {}
function fetch<T>(id: string): T
local result = cache[id]
if result then
return result::any
end
local result = {
id = id,
}
cache[id] = result
return result::any
end
function fetch2<T extends parentType>(id: string): T -- I don't like this, but this kind of functionality would be preferablle
local result = cache[id]
if result then
return result::any
end
local result = {
id = id,
}
cache[id] = result
return result::any
end
function tester()
local x: type1 = fetch("abc") -- current workaround, inherently unsafe because (see below)
local x: number = fetch("xyz") -- valid??
local z = fetch<type1>("abc") -- proposed
end
Thank you!
Joe