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: Support heterogeneous arrays #65

Open
dselman opened this issue Apr 9, 2024 · 1 comment
Open

Feature request: Support heterogeneous arrays #65

dselman opened this issue Apr 9, 2024 · 1 comment

Comments

@dselman
Copy link

dselman commented Apr 9, 2024

It would be very useful for some use cases to support serialisation / deserialisation of heterogeneous arrays (via type inheritance). For example:

@json
abstract class Animal {
  name!: string;
  type!: string; 
  // add a decorator to mark this as the type discrimator
  // or allow a callback in options to pass a method to return the type at runtime?
}

@json
class Dog extends Animal {
    age!: i32;
}

@json
class Cat extends Animal {
    isVerified!: boolean;
}

@json
class Zoo {
  animals!: Animal[]
}

export function parse(stringified: string) : string {
  const zoo = JSON.parse<Zoo>(stringified, true);
  const out = JSON.stringify<Zoo>(zoo);
  return out;
}

And:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="module">
      import { parse } from "./build/release.js";
      const zoo = {
        animals: [
          {
            name: "Fido",
            type: "Dog",
            age: 10,
          },
          {
            name: "Tiddles",
            type: "Cat",
            isVerified: false,
          },
        ],
      };
      try {
        document.body.innerText = parse(JSON.stringify(zoo));
      } catch (err) {
        alert(err);
      }
    </script>
  </head>
  <body></body>
</html>
@JairusSW
Copy link
Owner

I can do this. Hm, I'll have time this weekend

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