Heap.Optional
Makes an object's field optional (adds ?
to the resulting type of the object's property).
Optional fields can be omitted when creating a record, and they will not take any default value (the key simply won't exist in the object, and accessing it will return undefined
).
When reading (deserializing) a record, the default value (parameter default
) for optional fields is always ignored.
A pre-defined value of a top-level optional field can be reset by passing a value of null
in the update operation. This feature does not work for nullable fields, so it's advisable to avoid applying the Optional modifier to Union fields that may have a value of null
.
The Heap.Optional modifier is supported and makes sense only for Heap.Object fields and top-level table fields.
Usage / Signature
import { Heap } from '@app/heap'
Heap.Optional(fieldSchema)
Arguments
- <b id="fieldSchema">fieldSchema</b>:
HeapSchema
<b style="color:red">*</b>
A schema describing the "meaningful" type of the field that we are making optional. This can be any supported type of heap table field - simple or complex.
Return Value
The fieldSchema argument with the Optional modifier.
Examples
Optional Integer Field and Its Resetting
const customers = Heap.Table('customers', {
name: Heap.String(),
age: Heap.Optional(Heap.Number()),
})
await customers.create(ctx, { name: 'John Smith' })
// age = undefined
const mary = await customers.create(ctx, { name: 'Mary', age: 22 })
// age = 22
// Optional fields accept null to reset the value to undefined
await customers.update(ctx, { id: mary.id, age: null })
// age = undefined