Skip to content

Commit a10b1ba

Browse files
committed
Handle Maybe correctly in tuple encodings (fixes #49)
1 parent dd6aaac commit a10b1ba

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/Data/Aeson/TypeScript/TH.hs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -307,10 +307,15 @@ handleConstructor (ExtraTypeScriptOptions {..}) options (DatatypeInfo {..}) gene
307307
-- * Type declaration to use
308308
interfaceName = "I" <> (lastNameComponent' $ constructorName ci)
309309

310-
tupleEncoding =
310+
tupleEncoding = do
311+
let typ = contentsTupleTypeSubstituted genericVariables ci
312+
stringExp <- lift $ case typ of
313+
(AppT (ConT name) t) | name == ''Maybe -> [|$(getTypeAsStringExp t) <> " | null"|]
314+
_ -> getTypeAsStringExp typ
315+
311316
lift [|TSTypeAlternatives $(TH.stringE interfaceName)
312317
$(genericVariablesListExpr True genericVariables)
313-
[getTypeScriptType (Proxy :: Proxy $(return (contentsTupleTypeSubstituted genericVariables ci)))]
318+
[$(return stringExp)]
314319
$(tryGetDoc haddockModifier (constructorName ci))|]
315320

316321
assembleInterfaceDeclaration members = [|TSInterfaceDeclaration $(TH.stringE interfaceName)

test/Basic.hs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ data Unit2 = Unit2
1717
$(deriveTypeScript (A.defaultOptions { A.tagSingleConstructors = True
1818
, A.constructorTagModifier = const "foo" }) ''Unit2)
1919

20+
data Test1 = Test1 (Maybe Int)
21+
deriveTypeScript A.defaultOptions ''Test1
22+
2023
tests :: SpecWith ()
2124
tests = describe "Basic tests" $ do
2225
describe "tagSingleConstructors and constructorTagModifier" $ do
@@ -31,6 +34,12 @@ tests = describe "Basic tests" $ do
3134
TSTypeAlternatives "Unit2" [] ["\"foo\""] Nothing
3235
])
3336

37+
it [i|Maybe tuple encoding includes null option|] $ do
38+
(getTypeScriptDeclarations (Proxy :: Proxy Test1)) `shouldBe` ([
39+
TSTypeAlternatives "Test1" [] ["ITest1"] Nothing
40+
, TSTypeAlternatives "ITest1" [] ["number | null"] Nothing
41+
])
42+
3443

3544
main :: IO ()
3645
main = hspec tests

0 commit comments

Comments
 (0)