deepkit-framework
deepkit-framework copied to clipboard
[Feature] Serialization Consistency for Optional Properties
This is for a API pattern which keeps the consistency of fields, where every fields should be returned in the response no matter whether there is a value.
Currently the serialization behavior of optional fields varies based on whether the field is a constructor param:
test('null serialization consistency', async () => {
{
class MyEntity {
id: number & PrimaryKey & AutoIncrement = 0;
constructor(public name?: string) {}
}
const entity = new MyEntity();
expect(serialize<MyEntity>(entity)).toEqual({ id: 0, name: null }); // PASS
}
{
class MyEntity {
id: number & PrimaryKey & AutoIncrement = 0;
name?: string;
}
const entity = new MyEntity();
expect(serialize<MyEntity>(entity)).toEqual({ id: 0, name: null }); // FAIL
}
});
I think undefined
would be more correct
I think
undefined
would be more correct
JSON.stringify()
does not support undefined
, they will be directly ignored
I think the behaviour here is changed because when you do new MyEntity
with the constructor property, it will actually set the property to the prototype, not matter if undefined or not (this.name = name
), and with the non-constructor property it won't be visible in the prototype since no property assignment happens. The serializer uses the in
operator to check if the property is known and if not known it simply does not output it. Definitely unfortunate, but I don't know a solution right know. If you have any ideas, let me know.