fetch MessageType given its interface? #651
Replies: 2 comments
-
This is generally not possible in TypeScript, since all type information is erased at runtime. |
Beta Was this translation helpful? Give feedback.
-
You can get this to work, but only for objects (and nested objects) that were created via the protobuf-ts classes (e.g. import { containsMessageType, MESSAGE_TYPE } from '@protobuf-ts/runtime';
//... somehow acquire `data` object
if (containsMessageType(data)) {
const messageType = data[MESSAGE_TYPE];
console.log(messageToJson(data, messageType));
} Or put the logic into the import { containsMessageType, MESSAGE_TYPE } from '@protobuf-ts/runtime';
export function messageToJson<T extends object>(
message: T,
options?: Partial<Omit<JsonWriteOptions, 'emitDefaultValues'>>
) {
if (containsMessageType(message)) {
const messageType = message[MESSAGE_TYPE];
return messageType.toJson(message, { ...options, emitDefaultValues: true });
}
throw new Error('No MessageType on provided input');
} |
Beta Was this translation helpful? Give feedback.
-
I'm creating a schema registry, with the initial goal of simply validating that objects match their respective proto definition before being serialized and written anywhere.
Given that a developer would start with:
I'd like to implement a utility function that calls the right
toJson()
and uses some project-wideJsonWriteOptions
:Is there any way to get rid of the
messageType: IMessageType<T>
parameter here and infer it from the message?Beta Was this translation helpful? Give feedback.
All reactions