From a6fea2dd88ff80e4f53dd0dce4e414dca887278b Mon Sep 17 00:00:00 2001 From: Brooke Date: Thu, 24 Nov 2022 16:50:38 +0000 Subject: [PATCH 1/2] Add types to Option class --- modules/option/init.lua | 44 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/modules/option/init.lua b/modules/option/init.lua index bdda4450..c9ba934b 100644 --- a/modules/option/init.lua +++ b/modules/option/init.lua @@ -80,6 +80,41 @@ --]] +export type MatchTable = { + Some: (value: T) -> any, + None: () -> any, +} + +export type MatchFn = (matches: MatchTable) -> any + +export type DefaultFn = () -> T + +export type AndThenFn = (value: T) -> Option + +export type OrElseFn = () -> Option + +export type Option = typeof(setmetatable( + {} :: { + Match: (self: Option) -> MatchFn, + IsSome: (self: Option) -> boolean, + IsNone: (self: Option) -> boolean, + Contains: (self: Option, value: T) -> boolean, + Unwrap: (self: Option) -> T, + Expect: (self: Option, errMsg: string) -> T, + ExpectNone: (self: Option, errMsg: string) -> nil, + UnwrapOr: (self: Option, default: T) -> T, + UnwrapOrElse: (self: Option, defaultFn: DefaultFn) -> T, + And: (self: Option, opt2: Option) -> Option, + AndThen: (self: Option, predicate: AndThenFn) -> Option, + Or: (self: Option, opt2: Option) -> Option, + OrElse: (self: Option, orElseFunc: OrElseFn) -> Option, + XOr: (self: Option, opt2: Option) -> Option, + }, + {} :: { + __index: Option, + } +)) + local CLASSNAME = "Option" --[=[ @@ -444,4 +479,11 @@ end ]=] Option.None = Option._new() -return Option +return (Option :: any) :: { + Some: (value: T) -> Option, + Wrap: (value: T) -> Option, + + Is: (obj: any) -> boolean, + + None: Option, +} From 31d18771b7a194528fec0057ba3f87fc516140b9 Mon Sep 17 00:00:00 2001 From: Brooke Date: Thu, 24 Nov 2022 16:57:51 +0000 Subject: [PATCH 2/2] Fix type of `Option.None` --- modules/option/init.lua | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/option/init.lua b/modules/option/init.lua index c9ba934b..7b51ff04 100644 --- a/modules/option/init.lua +++ b/modules/option/init.lua @@ -485,5 +485,5 @@ return (Option :: any) :: { Is: (obj: any) -> boolean, - None: Option, + None: Option, }