Skip to content

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 schema
const Person = bin.object({
firstName: bin.string,
lastName: bin.string,
age: bin.i32,
});
// Writing a Person
Person.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 schema
const 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 Animal
Animal.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 animal
const 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 schema
const 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 => AnimalType
if (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}`);
}