how to handle optional properties correctly? #572
-
I am storing an object I receive from another API/Library. One of the properties is optional. When passed to Here is my schema: export const DISPLAY_USER_INFO_JSON_SCHEMA: JSONSchema = {
type: 'object',
properties: {
firstName: { type: 'string' },
lastName: { type: 'string' },
name: { type: 'string' },
partner: { type: 'string' },
passwordExpiration: { type: 'string' },
username: { type: 'string' },
},
required: ['name', 'partner', 'username'], // i originally did not have that, but that did not help
}; and here is my data from IndexDB: firstName: "Eric"
lastName: "Liprandi"
name: "Eric Liprandi"
partner: "snapfish"
passwordExpiration: undefined
username: "ericl" I tried returning How can I handle this situation directly with the library? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi, Currently, the JSON validator in the lib expects optional object properties to be inexistant: const user = {
firstName: "Eric",
lastName: "Liprandi",
name: "Eric Liprandi",
partner: "snapfish",
username: "ericl"
}; If it's not possible to directly get that from your other API, you can do: const user = {
firstName: "Eric",
lastName: "Liprandi",
name: "Eric Liprandi",
partner: "snapfish",
passwordExpiration: undefined,
username: "ericl"
};
if (user.passwordExpiration === undefined) {
delete user.passwordExpiration;
} Given that in TypeScript But while testing this solution, it appeared that the current lib behavior is preventing another issue: in some scenarios, the lib is forced to fallback to So it means you would not get the exact same value when reading back (as Also, more generally, So I'm not sure yet how and even if we should fix/add this feature. It needs further thinking. |
Beta Was this translation helpful? Give feedback.
Hi,
Currently, the JSON validator in the lib expects optional object properties to be inexistant:
If it's not possible to directly get that from your other API, you can do:
Given that in TypeScript
passwordExpiration?: string
is equivalent topasswordExpiration: string | undefined
, it would make sense to allow explicitu…