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

support newtype pattern in bindings #2156

Open
ctaggart opened this issue May 25, 2020 · 2 comments
Open

support newtype pattern in bindings #2156

ctaggart opened this issue May 25, 2020 · 2 comments

Comments

@ctaggart
Copy link
Contributor

Motivation

It would be more type-safe if we could wrap primitives using the newtype pattern. The API would then become:

pub struct KeyCode(pub i32);

extern {
  # [ wasm_bindgen ( method , getter , js_name = keyCode ) ] 
  pub fn key_code(this: &IKeyboardEvent) -> KeyCode; 
}

Currently, KeyCode is defined as an alias and the enum values becomes constants in a separate type.

https://github.com/taggartsoftware/ts2rs/blob/6d357315c915758f1e5a3c9af2d7e94b203e9fab/monaco-editor/src/monaco_extern.rs#L219-L220

https://github.com/taggartsoftware/ts2rs/blob/6d357315c915758f1e5a3c9af2d7e94b203e9fab/monaco-editor/src/monaco_help.rs#L22-L171

Proposed Solution

Is there way to see if it is a single value struct & wrap it accordingly?

Alternatives

Leave as is, which is less type safe.

Additional Context

This would be helpful for all TypeScript enums translated to wasm-bindgen. taggartsoftware/ts2rs#4

@Pauan
Copy link
Contributor

Pauan commented Jun 4, 2020

The user API would look something like this:

#[wasm_bindgen(transparent)]
pub struct KeyCode(i32);

This would apply a #[repr(transparent)] and generate the various trait impls.

@nasso
Copy link
Contributor

nasso commented Dec 28, 2021

Do we really need a wasm_bindgen(transparent) attribute if we already have #[repr(transparent)] (#1474)?

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

No branches or pull requests

3 participants