@@ -61,6 +61,15 @@ export type EncoderOptions<ContextType = undefined> = Partial<
61
61
*/
62
62
ignoreUndefined : boolean ;
63
63
64
+ /**
65
+ * If `true`, an object property with `undefined` value are encoded as `nil`, same as null.
66
+ * e.g. `{ foo: undefined }` will be encoded as `{ foo: nil }`.
67
+ * This flag has no effect if `ignoreUndefined` is `true`.
68
+ *
69
+ * Defaults to `true`.
70
+ */
71
+ undefinedAsNil : boolean ;
72
+
64
73
/**
65
74
* If `true`, integer numbers are encoded as floating point numbers,
66
75
* with the `forceFloat32` option taken into account.
@@ -82,6 +91,7 @@ export class Encoder<ContextType = undefined> {
82
91
private readonly forceFloat32 : boolean ;
83
92
private readonly ignoreUndefined : boolean ;
84
93
private readonly forceIntegerToFloat : boolean ;
94
+ private readonly undefinedAsNil : boolean ;
85
95
86
96
private pos : number ;
87
97
private view : DataView ;
@@ -99,6 +109,7 @@ export class Encoder<ContextType = undefined> {
99
109
this . sortKeys = options ?. sortKeys ?? false ;
100
110
this . forceFloat32 = options ?. forceFloat32 ?? false ;
101
111
this . ignoreUndefined = options ?. ignoreUndefined ?? false ;
112
+ this . undefinedAsNil = options ?. undefinedAsNil ?? true ;
102
113
this . forceIntegerToFloat = options ?. forceIntegerToFloat ?? false ;
103
114
104
115
this . pos = 0 ;
@@ -174,7 +185,9 @@ export class Encoder<ContextType = undefined> {
174
185
throw new Error ( `Too deep objects in depth ${ depth } ` ) ;
175
186
}
176
187
177
- if ( object == null ) {
188
+ if ( object === null ) {
189
+ this . encodeNil ( ) ;
190
+ } else if ( object === undefined && this . undefinedAsNil ) {
178
191
this . encodeNil ( ) ;
179
192
} else if ( typeof object === "boolean" ) {
180
193
this . encodeBoolean ( object ) ;
0 commit comments