Skip to content

Commit be2b032

Browse files
committed
fix: allow passing null or undefined to toBinary
Signed-off-by: Christian Stewart <christian@aperture.us>
1 parent 8ab0e2c commit be2b032

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

example/example.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,4 +231,16 @@ describe("EchoMsg", () => {
231231
const msg2 = EchoMsg.fromJsonString(jsonString);
232232
expect(msg).toEqual(msg2);
233233
});
234+
235+
it("toBinary with null returns empty Uint8Array", () => {
236+
const binary = EchoMsg.toBinary(null as any);
237+
expect(binary).toBeInstanceOf(Uint8Array);
238+
expect(binary.length).toBe(0);
239+
});
240+
241+
it("toBinary with undefined returns empty Uint8Array", () => {
242+
const binary = EchoMsg.toBinary(undefined as any);
243+
expect(binary).toBeInstanceOf(Uint8Array);
244+
expect(binary.length).toBe(0);
245+
});
234246
});

src/message.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,10 @@ export interface MessageType<T extends Message<T> = AnyMessage> {
151151
/**
152152
* Serialize the message to binary data.
153153
*/
154-
toBinary(a: Message<T>, options?: Partial<BinaryWriteOptions>): Uint8Array;
154+
toBinary(
155+
a: Message<T> | undefined | null,
156+
options?: Partial<BinaryWriteOptions>,
157+
): Uint8Array;
155158

156159
/**
157160
* Serialize the message to a JSON value, a JavaScript value that can be
@@ -286,7 +289,11 @@ export function createMessageType<
286289
return mt.fromJson(json, options);
287290
},
288291

289-
toBinary(a: T, options?: Partial<BinaryWriteOptions>): Uint8Array {
292+
toBinary(
293+
a: T | undefined | null,
294+
options?: Partial<BinaryWriteOptions>,
295+
): Uint8Array {
296+
if (a == null) return new Uint8Array(0);
290297
const opt = binaryMakeWriteOptions(options);
291298
const writer = opt.writerFactory();
292299
binaryWriteMessage(a, fields, writer, opt);

0 commit comments

Comments
 (0)