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

Feature Request: Structured enums to discriminated unions #2036

Open
everett1992 opened this issue Apr 15, 2024 · 0 comments
Open

Feature Request: Structured enums to discriminated unions #2036

everett1992 opened this issue Apr 15, 2024 · 0 comments

Comments

@everett1992
Copy link
Contributor

everett1992 commented Apr 15, 2024

I find that there are many API's written in rust with an enum variant parameter that I would write in TypeScript with a discriminated union or an overload

enum Event {
  Greeting { name: String },
  Birthday { name: String, age: u8 },
}

fn print(event: Event) {}
Discriminated union
type Event =
  | { type: 'greeting', name: string }
  | { type: 'birthday', age: number }
  
function print(event: Event) {}
Overload
function print(type: "greeting": params: { name: string })
function print(type: "birthday", params: { name: string, age: number})
function print(type: "greeting" | "birthday", params: { name: string, age?: number} ) {}

As far as I can tell this isn't possible with napi-rs today. Would this be easy to implement? Seems like it should be possible for structured enums as long as every member is a JsValue. Functions could support either overload and union style while recursive JsValues would always generate a discriminated union. The union would use the enum name as the type and the discriminating field type could be overriden. The identifiers could be overriden as well with js_name.


BTW thanks for developing this project

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

1 participant