-
|
Hi all. I am fairly new to luau types and have the following question: type Generic<V> = { -- arbitrary example
Value: V,
Value2: V,
Real: boolean,
}
type List = {
Example1: boolean,
Example2: number,
Example3: string,
}
-- where list is an arbitrary dictionary with string keys and any type values (as shown).
-- if possible, how to turn "List" type into:
type TransformedList = {
Example1: Generic<boolean>,
Example2: Generic<number>,
Example3: Generic<string>,
}
-- or some functionally identical equivalent
-- thanks for any help |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
I had a crack at this and talked to some Luau maintainers but there's still a key piece missing to make this possible: being able to call generic types. What that would look like, is inside a type function being able to call Without this piece, it's not very ergonomic to get what you want. You'd have to construct a type function and manually construct the In short, to get a good result you probably want to wait for the ability to call generic types to be implemented (there's no RFC afaik, but implementation might be coming in the next few months) |
Beta Was this translation helpful? Give feedback.
-
|
With the latest 0.676 release, this should now be possible! I wrote this type function to demonstrate: type function TransformList(ty)
if not ty:is("table") then
error(`expected argument #1 to TransformList to be a table, got {ty.tag}`)
end
local resultTable = types.newtable()
for key, value in ty:properties() do
if value.read ~= value.write then
error(`Key {key} had different read and write types, unknown what to do`)
end
resultTable:setproperty(key, Generic(value.read))
end
return resultTable
end
-- type TransformedList = { Example1: Generic<boolean> } now becomes
type TransformedList = TransformList<List>
-- TransformedList will be of type `{ Example1: { Value: boolean }, Example2: { Value: number }, Example3: { Value: string } }` one quick note is that this strips indexers, so you can potentially extend the type function to add that as well if you need it. |
Beta Was this translation helpful? Give feedback.
With the latest 0.676 release, this should now be possible!
I wrote this type function to demonstrate: