Hello, I want to disclose that the variable ‘callbackFunction’ is going to be a function however i cannot just input it as a function. How is this done?
Example:
type Function = (any) -> nil
function module:test(func: Function)
func()
end
--or
function module:test(func: (any) -> nil)
func()
end
Quick clarification: functions that return nothing don’t return nil
, they return void
. For example, a function that takes in a number and string and returns void would be annotated as:
(number, string) -> ()
The parameters can also be named, and you can have the function return any type. Unless the return is a tuple, you do not need to surround it with parenthesis:
(Value: number, Name: string) -> boolean
In your case, you would want to annotate callbackFunction
with (params) -> ()
.
Some more elaboration:
You can annotate the ellipsis (additional args) two different ways:
local foo: (a: any, ...b) -> c = function(a, ...) end
local function foo(a: any, ...: b): c end
Function generics are powerful:
function foo<T>(t: {T}): T?
return t[1]
end
foo{1, 2, 3} --the IDE will infer the return type to be number? because the table is of type {number}
To annotate OOP methods, just avoid using the colon shortcut:
type Object = {
foo: (self: Object, ...any) -> ()
}
function Class.foo(self: Object, ...: any): ()
end
--if you use the colon then it won't typecheck "self"
function Class:foo(...: any): ()
--what is self? never specified
end
Define overloadable functions using type intersection:
type foo = ((number) -> number) & ((number, number) -> string)
local foo: foo = function(a, b)
return if b then [[]] else 0/0
end
foo(1) --return type inferred to be number
foo(1, 2) --return type inferred to be string
You can chain the function literal; the precedence is from right to left
type foo = (a: boolean) -> (b: string) -> number
--same as (a: boolean) -> ((b: string) -> number)
local foo: foo = function(a: boolean)
return function(b: string): number
return 0.
end
end
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.