protobuf-es icon indicating copy to clipboard operation
protobuf-es copied to clipboard

Incorrect typing of Struct.toJson()

Open CharlieMartell opened this issue 1 year ago • 3 comments

Describe the bug

Here: https://github.com/bufbuild/protobuf-es/blob/main/packages/protobuf/src/google/protobuf/struct_pb.ts#L72 we see that this function returns a JsonValue type but in the implementation it should return a JsonObject type. This means consuming applications need get type errors when doing anything like Object.entries(struct.toJson())

CharlieMartell avatar Apr 04 '24 19:04 CharlieMartell

Also see: https://github.com/bufbuild/protobuf-es/issues/508

timostamm avatar Apr 05 '24 11:04 timostamm

Well this isn't about a better typing to the JSON its just that the return value of this fn is just wrong. It only ever returns a JsonObject type

CharlieMartell avatar Apr 05 '24 17:04 CharlieMartell

It is not wrong because a JsonObject is a JsonValue. Here's the definition:

export type JsonValue =
  | number
  | string
  | boolean
  | null
  | JsonObject
  | JsonValue[];

export type JsonObject = { [k: string]: JsonValue };

All messages actually return a JsonObject, the only exception are a handful of well-known types. We use JsonValue for both sides for symmetry, it was never intended to provide message-specific type information.

timostamm avatar Apr 06 '24 12:04 timostamm