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

Internally tagged enums can generate invalid TS when using non-object types #7

Open
Alfred-Mountfield opened this issue Aug 29, 2022 · 1 comment
Labels
enhancement New feature or request

Comments

@Alfred-Mountfield
Copy link

If you have an enum such as this:

#[derive(Debug, Serialize, Deserialize, Tsify)]
#[serde(tag = "reason")]
pub enum ParseBaseUriError {
    MissingTrailingSlash,
    UrlParseError(String),
    CannotBeABase,
}

then the generated types look as follows:

declare namespace ParseBaseUriError {
    export type MissingTrailingSlash = { reason: "MissingTrailingSlash" };
    export type UrlParseError = { reason: "UrlParseError" } & string;
    export type CannotBeABase = { reason: "CannotBeABase" };
}

And I believe UrlParseError is unsatisfiable.

I don't really have a good suggestion for how to resolve this, perhaps disallowing new-type like variants, or possibly only ones that contain types that can be mapped to a non-object JS type. For now I have resolved this by picking a different tagging mechanism, or turning the variants into structs, but I thought I'd flag in case there are any other ideas or to allow adding a warning.

@madonoharu madonoharu added the enhancement New feature or request label Aug 29, 2022
@jkomyno
Copy link

jkomyno commented Oct 16, 2022

I have also noted the same issue, which can quickly be avoided by using both tag and content, e.g., something like
#[serde(tag = "_tag", content = "value")]. With your example above:

#[derive(Debug, Serialize, Deserialize, Tsify)]
#[serde(rename_all = "camelCase", tag = "_tag", content = "value")]
#[tsify(into_wasm_abi, from_wasm_abi)]
pub enum ParseBaseUriError {
  MissingTrailingSlash,
  UrlParseError(String),
  CannotBeABase,
}

results in the following type declaration:

// you can pattern-match on the `_tag` property
export type ParseBaseUriError
  = { _tag: "missingTrailingSlash" }
  | { _tag: "urlParseError", value: string }
  | { _tag: "cannotBeABase" }

carlsverre pushed a commit to carlsverre/tsify that referenced this issue Jan 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants