From 9fa93336840771714db8888a06264b26bed8adfe Mon Sep 17 00:00:00 2001 From: Oscar Beaumont Date: Thu, 9 May 2024 10:33:47 +0800 Subject: [PATCH] fix empty enum variants --- src/lang/ts/mod.rs | 12 ++++++++---- tests/ts.rs | 36 ++++++++++++++++++++++++------------ 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/lang/ts/mod.rs b/src/lang/ts/mod.rs index e245142..f47647e 100644 --- a/src/lang/ts/mod.rs +++ b/src/lang/ts/mod.rs @@ -661,15 +661,19 @@ fn enum_datatype(ctx: ExportContext, e: &EnumType, type_map: &TypeMap) -> Output format!("{{ {tag}: {sanitised_name} }}") } (EnumRepr::Adjacent { tag, content }, _) => { - let ts_values = enum_variant_datatype( + let ts_value = enum_variant_datatype( ctx.with(PathItem::Variant(variant_name.clone())), type_map, variant_name.clone(), variant, - )? - .expect("Invalid Serde type"); + )?; - format!("{{ {tag}: {sanitised_name}; {content}: {ts_values} }}") + let mut result = format!("{{ {tag}: {sanitised_name}"); + if let Some(ts_value) = ts_value { + result.push_str(&format!("; {content}: {ts_value}")); + } + result.push_str(" }"); + result } }, true, diff --git a/tests/ts.rs b/tests/ts.rs index 5e54c82..55cf0fe 100644 --- a/tests/ts.rs +++ b/tests/ts.rs @@ -261,6 +261,23 @@ fn typescript_types() { assert_ts!(ExtraBracketsInTupleVariant, "{ A: string }"); assert_ts!(ExtraBracketsInUnnamedStruct, "string"); + // https://github.com/oscartbeaumont/specta/issues/156 + assert_ts!(Vec, r#"({ A: string } | { B: number })[]"#); + + assert_ts!(InlineTuple, r#"{ demo: [string, boolean] }"#); + assert_ts!( + InlineTuple2, + r#"{ demo: [{ demo: [string, boolean] }, boolean] }"# + ); + + // https://github.com/oscartbeaumont/specta/issues/220 + assert_ts!(Box, r#"string"#); + + assert_ts!( + SkippedFieldWithinVariant, + r#"{ type: "A" } | { type: "B"; data: string }"# + ); + // https://github.com/oscartbeaumont/specta/issues/90 assert_ts!(RenameWithWeirdCharsField, r#"{ "@odata.context": string }"#); assert_ts!( @@ -291,18 +308,6 @@ fn typescript_types() { r#"@odata.context"#.to_string() ) ); - - // https://github.com/oscartbeaumont/specta/issues/156 - assert_ts!(Vec, r#"({ A: string } | { B: number })[]"#); - - assert_ts!(InlineTuple, r#"{ demo: [string, boolean] }"#); - assert_ts!( - InlineTuple2, - r#"{ demo: [{ demo: [string, boolean] }, boolean] }"# - ); - - // https://github.com/oscartbeaumont/specta/issues/220 - assert_ts!(Box, r#"string"#); } #[derive(Type)] @@ -644,3 +649,10 @@ pub struct InlineTuple2 { #[specta(inline)] demo: (InlineTuple, bool), } + +#[derive(Type)] +#[serde(tag = "type", content = "data")] +pub enum SkippedFieldWithinVariant { + A(#[serde(skip)] String), + B(String), +}