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

Add a 'quote' attribute to generate quoted TS properties #46

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ Tsify field attributes

- `type`
- `optional`
- `quote`

Serde attributes

Expand Down Expand Up @@ -141,6 +142,27 @@ export interface Optional {
}
```

## Quoted Properties

`#[tsify(quote)]` puts the resulting TypeScript property in quotes. This can be useful if, for example, `#[serde(rename)]` results in a property that is not a valid identifier in TypeScript.

```rust
#[derive(Tsify)]
struct Quoted {
#[serde(rename = "with spaces")]
#[tsify(quote)]
with_spaces: i32
}
```

Generated type:

```ts
export interface Quoted {
"with spaces": number;
}
```

## Enum

```rust
Expand Down
34 changes: 34 additions & 0 deletions tests/quote.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#![allow(dead_code)]

use indoc::indoc;
use pretty_assertions::assert_eq;
use tsify::Tsify;

#[test]
fn test_quote() {
#[derive(Tsify)]
struct QuotedStruct {
#[serde(rename = "with spaces")]
#[tsify(quote)]
with_spaces: i32,

#[serde(rename = "with-hyphen")]
#[tsify(quote)]
with_hyphen: i32,

#[serde(rename = "@invalid!ident")]
#[tsify(quote)]
invalid_ident: i32,
}

assert_eq!(
QuotedStruct::DECL,
indoc! { r#"
export interface QuotedStruct {
"with spaces": number;
"with-hyphen": number;
"@invalid!ident": number;
}"#
}
);
}
10 changes: 10 additions & 0 deletions tsify-macros/src/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ impl TsifyContainerAttars {
pub struct TsifyFieldAttrs {
pub type_override: Option<String>,
pub optional: bool,
pub quote: bool,
}

impl TsifyFieldAttrs {
pub fn from_serde_field(field: &Field) -> syn::Result<Self> {
let mut attrs = Self {
type_override: None,
optional: false,
quote: false,
};

for attr in &field.original.attrs {
Expand All @@ -92,6 +94,14 @@ impl TsifyFieldAttrs {
return Ok(());
}

if meta.path.is_ident("quote") {
if attrs.quote {
return Err(meta.error("duplicate attribute"));
}
attrs.quote = true;
return Ok(());
}

Err(meta.error("unsupported tsify attribute, expected one of `type` or `optional`"))
})?;
}
Expand Down
5 changes: 4 additions & 1 deletion tsify-macros/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,10 +211,13 @@ impl<'a> Parser<'a> {
let key = field.attrs.name().serialize_name();
let (type_ann, field_attrs) = self.parse_field(field);

let optional = field_attrs.map_or(false, |attrs| attrs.optional);
let (optional, quote) =
field_attrs.map_or((false, false), |attrs| (attrs.optional, attrs.quote));
let default_is_none = self.container.serde_attrs().default().is_none()
&& field.attrs.default().is_none();

let key = if quote { format!("\"{}\"", key) } else { key };

let type_ann = if optional {
match type_ann {
TsType::Option(t) => *t,
Expand Down
6 changes: 5 additions & 1 deletion tsify-macros/src/typescript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -578,14 +578,18 @@ fn is_js_ident(string: &str) -> bool {
!string.contains('-')
}

fn is_quoted(string: &str) -> bool {
string.starts_with('"') && string.ends_with('"')
}

impl Display for TsTypeElement {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let key = &self.key;
let type_ann = &self.type_ann;

let optional_ann = if self.optional { "?" } else { "" };

if is_js_ident(key) {
if is_js_ident(key) || is_quoted(key) {
write!(f, "{key}{optional_ann}: {type_ann}")
} else {
write!(f, "\"{key}\"{optional_ann}: {type_ann}")
Expand Down