I am wondering how it is possible to use ...any
like so, { ...any }
, in a table?
3 Likes
type Pair <a,b> = {
first : a
second : b
}
The Pair is basically a table accepting any type that you supply through a function when you supply 2 parameters
2 Likes
What if there’s a third
? Can’t keep adding
1 Like
type tblGeneric<K, V> = {[K]: V}
local myTbl: tblGeneric<any, any>
Something like this? K is key type, V is value type
You can add as many as you like as long there are enough ‘types’ for them
type Pair <a,b,c,d>= {
first : a
second : b
third : c
fourth : d
}
The ...
is only used for variadic arguments and in returned values. You cannot use ...
in an array since you can only define the entire array’s value type, so you would have to use {any}
.
--!strict
-- any type
local function foo(...: any): ...any
return ...
end
local arg1, arg2 = foo(1, 2) -- typed as ...any
print(arg1, arg2) -- 1, 2
local function foo(...: any): {any}
return {...}
end
local args = foo(1, 2) -- typed as {any}
print(args[1], args[2]) -- 1, 2
-- generic type
local function bar<T>(...: T): (...T)
return ...
end
local arg1, arg2 = bar(1, 2) -- typed as ...number
print(arg1, arg2) -- 1, 2
local function bar<T>(...: T): {T}
return {...}
end
local args = bar(1, 2) -- typed as {number}
print(args[1], args[2])
1 Like
If you’d like a dictionary with some defined types but allow new items without making Luau angry:
type myTable = {
example1: number,
example2: boolean,
[string]: any -- Additional items are okay
}
1 Like
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.