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

Typed JSON #508

Open
Palmik opened this issue Jun 18, 2023 · 3 comments
Open

Typed JSON #508

Palmik opened this issue Jun 18, 2023 · 3 comments
Labels
Wishlist Things we'd want in the future

Comments

@Palmik
Copy link

Palmik commented Jun 18, 2023

It would be nice and useful to have types generated for objects produced by toJson, rather than just having a generic type like today.

@smaye81
Copy link
Member

smaye81 commented Jun 21, 2023

Hi @Palmik this has been requested a few times. It's probably something we should consider. Going to keep this open so we can eventually prioritize.

@FND
Copy link

FND commented Apr 2, 2024

FWIW, I've run into the same issue and resorted to deriving data structures from classes. However, that's not just brittle, it also feels like solving the problem at the wrong layer because the compiler should already know what these data structures look like.

source code
// given the following class hierarchy...

import { Message } from "@bufbuild/protobuf";

class Person extends Message<Person> {
    name?: string;
    age?: number;
    address?: Address;
}

class Address extends Message<Address> {
    country?: string;
    location?: string;
}

// ... we want to generate a type containing only the respective data fields

let data: PersonData = {
    name: "JD",
    age: 123,
    address: {
        country: "Nirvana",
        location: "ether"
    }
};

// ... so we derive data structures from the respective classes

type PersonData = DataOnly<Person>;
type AddressData = DataOnly<Address>; // for testing purposes only

type DataOnly<T extends OptionalMessage> = T extends Message ? {
        [Key in Exclude<keyof T, keyof Message>]: T[Key] extends OptionalMessage
            ? DataOnly<T[Key]>
            : T[Key];
    }
    : undefined;
type OptionalMessage = Message | undefined;

// ... except properties' optional flag is lost

data = {
    name: "JD",
    age: 123
};

@Zetanova
Copy link

I run into an issue with IndexedDb used over dexie.js

To use a generic JsonValue inside the stored data type then the the query and patch feature of dexie is not type-safe.

The PlainMessage<MyMessage> is useable (not optimal) but brings other issues
dexie/Dexie.js#2001

To generate a typed Interface for the JsonValue with the correct used json_name would be optimal in this regard.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Wishlist Things we'd want in the future
Projects
None yet
Development

No branches or pull requests

4 participants