Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix flatten generic by changing TS::name #235

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ impl DerivedTS {
.unwrap_or_else(TokenStream::new);

let impl_start = generate_impl(&rust_ty, &generics);
let generic_idents = generics.type_params().map(|x| x.ident.clone());
quote! {
#impl_start {
const EXPORT_TO: Option<&'static str> = Some(#export_to);
Expand All @@ -108,7 +109,11 @@ impl DerivedTS {
#decl
}
fn name() -> String {
#name.to_owned()
let generics: Vec<String> = vec![#(<#generic_idents>::name()),*];
match generics.is_empty() {
true => #name.to_owned(),
false => format!("{}<{}>", #name, generics.join(", ")),
}
}
fn inline() -> String {
#inline
Expand Down
11 changes: 4 additions & 7 deletions macros/src/types/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,12 @@ pub fn format_type(ty: &Type, dependencies: &mut Dependencies, generics: &Generi
}

return quote!(
match <#generic_ident>::inline().as_str() {
// When exporting a generic, the default type used is `()`,
// which gives "null" when calling `.name()`. In this case, we
// want to preserve the type param's identifier as the name used
match <#generic_ident>::name().as_str() {
"null" => #generic_ident_str.to_owned(),

// If name is not "null", a type has been provided, so we use its
// name instead
x => x.to_owned()
x => {
x.to_owned()
}
Comment on lines +67 to +72
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to re-add comments later

}
);
}
Expand Down
22 changes: 17 additions & 5 deletions ts-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,10 @@ pub trait TS {

/// Name of this type in TypeScript, with type arguments.
fn name_with_type_args(args: Vec<String>) -> String {
format!("{}<{}>", Self::name(), args.join(", "))
match Self::name().split_once('<') {
None => Self::name(),
Some(x) => format!("{}<{}>", x.0, args.join(", "))
}
}

/// Formats this types definition in TypeScript, e.g `{ user_id: number }`.
Expand Down Expand Up @@ -397,7 +400,10 @@ impl Dependency {
let exported_to = T::get_export_to()?;
Some(Dependency {
type_id: TypeId::of::<T>(),
ts_name: T::name(),
ts_name: match T::name() {
x if !x.contains('<') => x,
x => x.split('<').next().unwrap().to_owned()
},
Comment on lines +403 to +406
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dependency seems to need the name without any generics, so the same hacky approach was used here

exported_to,
})
}
Expand Down Expand Up @@ -535,7 +541,7 @@ impl<T: TS, E: TS> TS for Result<T, E> {

impl<T: TS> TS for Vec<T> {
fn name() -> String {
"Array".to_owned()
format!("Array<{}>", T::name())
}

fn inline() -> String {
Expand All @@ -561,7 +567,13 @@ impl<T: TS, const N: usize> TS for [T; N] {
return Vec::<T>::name();
}

"[]".to_owned()
format!(
"[{}]",
(0..N)
.map(|_| T::name())
.collect::<Box<[_]>>()
.join(", ")
)
}

fn name_with_type_args(args: Vec<String>) -> String {
Expand Down Expand Up @@ -610,7 +622,7 @@ impl<T: TS, const N: usize> TS for [T; N] {

impl<K: TS, V: TS, H> TS for HashMap<K, V, H> {
fn name() -> String {
"Record".to_owned()
format!("Record<{}, {}>", K::name(), V::name())
}

fn name_with_type_args(args: Vec<String>) -> String {
Expand Down
35 changes: 34 additions & 1 deletion ts-rs/tests/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ fn default() {
// #[ts(inline)]
// xi2: X<i32>
}
assert_eq!(Y::decl(), "type Y = { a1: A, a2: A<number>, }")
assert_eq!(Y::decl(), "type Y = { a1: A<string>, a2: A<number>, }")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side effect: The generic is always emitted, even when using its default

}

#[test]
Expand Down Expand Up @@ -349,3 +349,36 @@ fn deeply_nested() {
}"
);
}

#[test]
fn inline_generic_enum() {
#[derive(TS)]
struct OtherType<T>(T);

#[derive(TS)]
struct SomeType<T>(OtherType<T>);

#[derive(TS)]
enum MyEnum<A, B> {
VariantA(A),
VariantB(B)
}

#[derive(TS)]
struct Parent {
e: MyEnum<i32, i32>,
#[ts(inline)]
e1: MyEnum<i32, SomeType<String>>
}

// This fails!
// The #[ts(inline)] seems to inline recursively, so not only the definition of `MyEnum`, but
// also the definition of `SomeType`.
assert_eq!(
Parent::decl(),
"type Parent = { \
e: MyEnum<number, number>, \
e1: { \"VariantA\": number } | { \"VariantB\": SomeType<string> }, \
}"
);
}
32 changes: 32 additions & 0 deletions ts-rs/tests/type_alias.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#![allow(dead_code)]

use std::collections::HashMap;
use ts_rs::TS;

type TypeAlias = HashMap<String, String>;

#[derive(TS)]
enum Enum {
A(TypeAlias),
B(HashMap<String, String>),
}

#[derive(TS)]
struct Struct {
a: TypeAlias,
b: HashMap<String, String>
}

#[test]
fn type_alias() {
assert_eq!(
Enum::decl(),
r#"type Enum = { "A": Record<string, string> } | { "B": Record<string, string> };"#
);

assert_eq!(
Struct::decl(),
"type Struct = { a: Record<string, string>, b: Record<string, string>, }"
);
}

Loading