diff --git a/macros/src/type/attr/field.rs b/macros/src/type/attr/field.rs index 7e39e51f..3db4748d 100644 --- a/macros/src/type/attr/field.rs +++ b/macros/src/type/attr/field.rs @@ -40,6 +40,7 @@ impl_parse! { "skip_deserializing" => out.skip = true, "skip_serializing_if" => out.optional = attr.parse_string()? == *"Option::is_none", "optional" => out.optional = attr.parse_bool().unwrap_or(true), + "default" => out.optional = attr.parse_bool().unwrap_or(true), "flatten" => out.flatten = attr.parse_bool().unwrap_or(true) } } diff --git a/src/lang/ts/mod.rs b/src/lang/ts/mod.rs index 9067be11..ed23019d 100644 --- a/src/lang/ts/mod.rs +++ b/src/lang/ts/mod.rs @@ -254,25 +254,7 @@ fn object_datatype( let mut unflattened_fields = fields .iter() .filter(|f| !f.flatten) - .map(|field| { - let ctx = ctx.with(PathItem::Field(field.key)); - let field_name_safe = sanitise_key(field.key, false); - let field_ts_str = datatype_inner(ctx, &field.ty); - - // https://github.com/oscartbeaumont/rspc/issues/100#issuecomment-1373092211 - let (key, result) = match field.optional { - true => ( - format!("{field_name_safe}?"), - match &field.ty { - DataType::Nullable(_) => field_ts_str, - _ => field_ts_str.map(|v| format!("{v} | null")), - }, - ), - false => (field_name_safe, field_ts_str), - }; - - result.map(|v| format!("{key}: {v}")) - }) + .map(|f| object_field_to_ts(ctx.with(PathItem::Field(f.key)), f)) .collect::, _>>()?; if let Some(tag) = tag { @@ -384,14 +366,9 @@ impl LiteralType { fn object_field_to_ts(ctx: ExportContext, field: &ObjectField) -> Result { let field_name_safe = sanitise_key(field.key, false); + // https://github.com/oscartbeaumont/rspc/issues/100#issuecomment-1373092211 let (key, ty) = match field.optional { - true => ( - format!("{field_name_safe}?"), - match &field.ty { - DataType::Nullable(ty) => ty, - ty => ty, - }, - ), + true => (format!("{field_name_safe}?"), &field.ty), false => (field_name_safe, &field.ty), }; diff --git a/tests/ts_rs/optional_field.rs b/tests/ts_rs/optional_field.rs index f7bb033b..847e5155 100644 --- a/tests/ts_rs/optional_field.rs +++ b/tests/ts_rs/optional_field.rs @@ -10,12 +10,14 @@ struct Optional { b: Option, #[serde(skip_serializing_if = "Option::is_none")] c: Option, + #[serde(default)] + d: bool, } #[test] fn test() { assert_ts!( Optional, - "{ a: number | null; b?: number | null; c?: string | null }" + "{ a: number | null; b?: number | null; c?: string | null; d?: boolean }" ); }