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

How to define TypeDef for types like uuid::Uuid? #28

Closed
greatcat19 opened this issue Nov 19, 2023 · 2 comments
Closed

How to define TypeDef for types like uuid::Uuid? #28

greatcat19 opened this issue Nov 19, 2023 · 2 comments

Comments

@greatcat19
Copy link

Hello!

I tried to do something like this:

impl TypeDef for Uuid {
    const INFO: TypeInfo = TypeInfo::Native(NativeTypeInfo {
        r#ref: TypeExpr::ident(Ident("string")),
    });
}

But it shows:

`Uuid` is not defined in the current craterustc[E0117](https://doc.rust-lang.org/error-index.html#E0117)
@dbeckwith
Copy link
Owner

As the Rust error code is indicating, you are running into a common constraint in Rust called the "orphan rule". You can't implement a foreign trait for a foreign type, because there's nothing preventing a different crate from doing the same thing and defining a conflicting implementation.

A common way to get around this is to create a local "newtype" wrapper around the type and use this instead. This is the approach I take in most of my projects, as it gives you a lot of control over other aspects of your type as well.

#[derive(Debug, Serialize, Deserialize)]
pub struct MyId(pub uuid::Uuid);

impl TypeDef for MyId {
    const INFO: TypeInfo = TypeInfo::Native(NativeTypeInfo {
        r#ref: TypeExpr::ident(Ident("string")),
    });
}

Another approach you can use is to tell the TypeDef macro to use a different type for the Typescript type wherever you mention Uuid:

#[derive(Serialize, Deserialize, TypeDef)]
pub struct MyStruct {
  #[type_def(type_of = "String")]
  pub id: Uuid;
  pub foo: usize;
}

You can also combine the two if you want to use a newtype but don't want to implement TypeDef manually:

#[derive(Debug, Serialize, Deserialize, TypeDef)]
pub struct MyId(#[type_def(type_of = "String")] pub uuid::Uuid);

@greatcat19
Copy link
Author

Thank you so much, @dbeckwith !
The second approach is exactly what I've been looking for!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants