Objects
Primitive values in JavaScript can be composed into Plain-Old-JavaScript-Objects. This can be
easily represented using the bin.object()
schema constructor function.
Simple objects
import bin from 'typed-binary';
// Simple object schemaconst Person = bin.object({ firstName: bin.string, lastName: bin.string, age: bin.i32,});
// Writing a PersonPerson.write(writer, { firstName: 'John', lastName: 'Doe', age: 43,});
console.log(JSON.stringify(Person.read(reader))); // { "firstName": "John", ... }
Generic objects
This feature allows for the parsing of a type that contains different fields depending on its previous values. For example, if you want to store an animal description, certain animal types might have differing features from one another.
Keyed by strings
import bin from 'typed-binary';
// Generic object schemaconst Animal = bin.generic( { nickname: bin.string, age: bin.i32, }, { dog: bin.object({ // Animal can be a dog breed: bin.string, }), cat: bin.object({ // Animal can be a cat striped: bin.bool, }), });
// Writing an AnimalAnimal.write(writer, { type: 'cat', // We're specyfing which concrete type we want this object to be.
// Base properties nickname: 'James', age: 5,
// Concrete type specific properties striped: true,});
// Deserializing the animalconst animal = Animal.read(reader);console.log(JSON.stringify(animal)); // { "age": 5, "striped": true ... }
// -- Type checking works here! --// animal.type => 'cat' | 'dog'if (animal.type === 'cat') { // animal.type => 'cat' console.log("It's a cat!"); // animal.striped => bool console.log(animal.striped ? 'Striped' : 'Not striped');} else { // animal.type => 'dog' console.log("It's a dog!"); // animal.breed => string console.log(`More specifically, a ${animal.breed}`);
// This would result in a type error (Static typing FTW!) // console.log(`Striped: ${animal.striped}`);}
Keyed by an enum (byte)
import bin from 'typed-binary';
enum AnimalType = { DOG = 0, CAT = 1,};
// Generic (enum) object schemaconst Animal = bin.genericEnum({ nickname: bin.string, age: bin.i32,}, { [AnimalType.DOG]: bin.object({ // Animal can be a dog breed: bin.string, }), [AnimalType.CAT]: bin.object({ // Animal can be a cat striped: bin.bool, }),});
// ...// Same as for the string keyed case// ...
// -- Type checking works here! --// animal.type => AnimalTypeif (animal.type === AnimalType.CAT) { // animal.type => AnimalType.CAT console.log("It's a cat!"); // animal.striped => bool console.log(animal.striped ? "Striped" : "Not striped");}else { // animal.type => AnimalType.DOG console.log("It's a dog!"); // animal.breed => string console.log(`More specifically, a ${animal.breed}`);
// This would result in a type error (Static typing FTW!) // console.log(`Striped: ${animal.striped}`);}