It’s possible to automatically make yourself a type without having to type it all in type annotation.
local test = {
a = function()
return "value"
end,
}
export type test = typeof(test)
Now for Union Types, like this.
export type test = "a" | "b" | "c"
function check(value: test)
end
the type checker thinks now that the value’s could either be, a,b,c as strings
And I was wondering how to turn this into a type check though.
local test = {"a", "b", "c"}
To achieve the same thing.
Not sure how. Not even sure if Generics can somehow be used to achieve this or not.
poolhail
(pool)
September 1, 2023, 10:05pm
#2
Not sure if I understand the question but if I wanted to type-check
local test = {"a", "b", "c"}
it would just be
local test: {string} = {"a", "b", "c"}
nicemike40
(nicemike40)
September 1, 2023, 10:48pm
#3
I do not believe there is a way to do this in Luau, no.
There is an issue opened in the Luau repo suggesting related functionality:
opened 05:10PM - 24 Jun 23 UTC
enhancement
# The problem
Currently, it's inconvenient to type check table content as I hav… e to write the same thing twice, both in the type declaration and in the table.
For instance, a constant that use a bunch of strings as keys.
```lua
type PossibleOpinions = 'Cats'|'Dogs'|'Pizzas'|'Tacos'
local MY_OPINIONS = {
['Cats'] = 'I love cats!',
['Dogs'] = 'I like dogs! But I prefer cats!',
['Pizzas'] = 'When I think about pizzas I think about Peppino Spaghetti',
['Tacos'] = 'You mean that french dish where they put a bunch of stuff in a brick?'
}
function sayMyOpinion(about:PossibleOpinions)
print(MY_OPINIONS[about])
end
sayMyOpinion('Cats') -- ok
sayMyOpinion('Hexagons') -- not ok
```
# The solution
Add a **keyof** type! It returns a union of all the keys of a table!
It should be backward compatible like **typeof** and not so chaotic to integrate.
```lua
local MY_OPINIONS = {
['Cats'] = 'I love cats!',
['Dogs'] = 'I like dogs! But I prefer cats!',
['Pizzas'] = 'When I think about pizzas I think about Peppino Spaghetti',
['Tacos'] = 'You mean that french dish where they put a bunch of stuff in a brick?'
}
function sayMyOpinion(about:keyof(MY_OPINIONS))
print(MY_OPINIONS[about])
end
sayMyOpinion('Cats') -- ok
sayMyOpinion('Hexagons') -- not ok
```
Your specific use-case would also require a way to mark an array-like table as sealed (or perhaps automatically detect table.freeze
in the same way typescript has as const
)
1 Like