Optionals
Optionals are a good way of ensuring that no excessive data is stored as binary.
They are encoded as:
0
givenvalue === undefined
.1 encoded(value)
givenvalue !== undefined
.
import bin from 'typed-binary';
const buffer = Buffer.alloc(16);const writer = new bin.BufferWriter(buffer);const reader = new bin.BufferReader(buffer);
// Simple object schemaconst Address = bin.object({ city: bin.string, street: bin.string, postalCode: bin.string,});
// Simple object schema (with optional field)const Person = bin.object({ firstName: bin.string, lastName: bin.string, age: bin.i32, address: bin.optional(Address),});
// Writing a Person (no address)Person.write(writer, { firstName: 'John', lastName: 'Doe', age: 43,});
// Writing a Person (with an address)Person.write(writer, { firstName: 'Jesse', lastName: 'Doe', age: 38, address: { city: 'New York', street: 'Binary St.', postalCode: '11-111', },});
console.log(JSON.stringify(Person.read(reader).address)); // undefinedconsole.log(JSON.stringify(Person.read(reader).address)); // { "city": "New York", ... }