Logo

dev-resources.site

for different kinds of informations.

How to Speak Binary in TypeScript

Published at
5/13/2021
Categories
typescript
binary
encoding
serialization
Author
voltrevo
Author
8 person written this
voltrevo
open
How to Speak Binary in TypeScript

If you're sending or receiving data in TypeScript, chances are high that you are using JSON:

const awesomeData = {
  direction: 'up',
  distance: 1000,
};

const json = JSON.stringify(awesomeData);

send(json);
Enter fullscreen mode Exit fullscreen mode

JSON is nice for two reasons:

  1. You can read it ({"direction":"up","distance":1000} is pretty explicit).
  2. JSON doesn't take anything to set up, it's just there.

However, this simple utility doesn't play very nicely with TypeScript:

const json = receive();

// { direction:'up', distance: 1000 }
const awesomeData = JSON.parse(json);

// TypeScript compiler: "Sure, why not?"
awesomeData.direction = 1;
Enter fullscreen mode Exit fullscreen mode

JSON.parse is one of those APIs that opts out of type checking - it returns any, which means TypeScript knows nothing about it, but will let us do anything with it.

That's not cool. We're using TypeScript to avoid exactly this problem.

There is a better way:

import * as tb from 'typed-bytes';

const Awesome = tb.object({
  direction: tb.enum_('up', 'down', 'left', 'right'),
  distance: tb.size,
});

type Awesome = tb.TypeOf<typeof Awesome>;

function sendData() {
  const awesomeData: Awesome = {
    direction: 'up',
    distance: 1000,
  };

  // Here encodeBuffer knows that awesomeData needs to match type Awesome
  const buffer = tb.encodeBuffer(Awesome, awesomeData);

  send(buffer);
}

function receiveData() {
  const buffer = receive();

  const awesomeData = tb.decodeBuffer(Awesome, buffer);

  // Error: Type '1' is not assignable to type '"up" | "down" | "left" | "right"'
  awesomeData.direction += 1;
}
Enter fullscreen mode Exit fullscreen mode

Hooray, now awesomeData is correctly type checked 🎉.

It's not just that though. Take a closer look at buffer:

ArrayBuffer { [Uint8Contents]: <00 e8 07>, byteLength: 3 }
Enter fullscreen mode Exit fullscreen mode

Three bytes. That's all we needed. In JSON we used 34 bytes.

Why not just use Protocol Buffers?

I'm glad you asked. typed-bytes is a public domain library that lives at typedbytes.org. There's a detailed comparison over there 😉.

serialization Article's
30 articles in total
Favicon
Java interacting with Apache Avro
Favicon
Apache Avro
Favicon
Protocol Buffers as a Serialization Format
Favicon
WSON (Web Simple Object Notation)
Favicon
Serializing Python Object Using the pickle Module
Favicon
Converting a Unicorn project to Sitecore Content Serialization (SCS)
Favicon
Converting a TDS project to Sitecore Content Serialization (SCS) 
Favicon
Deserializing Polymorphic Lists with Kotlin, Jackson, and Spring Boot
Favicon
Mapify-ts
Favicon
ProtoBuf message serialization in Akka.NET using protobuf-net
Favicon
Pandas Dataframe to AVRO
Favicon
Mapping > Json Converters // true
Favicon
Nested Encoding Efficency
Favicon
Java serialization with Avro
Favicon
Java Serialization with Flatbuffers
Favicon
Java Serialization with Protocol Buffers
Favicon
Serialização de Objectos
Favicon
Effective Java: Consider Serialization Proxies Instead of Serialized Instances
Favicon
Effective Java: For Instance Control, Prefer Enum types to readResolve
Favicon
Effective Java: Write readObject Methods Defensively
Favicon
Effective Java: Consider Using a Custom Serialized Form
Favicon
Effective Java: Prefer Alternatives To Java Serialization
Favicon
ASP.NET XML serialisation issues: Observations on DataContractSerializer
Favicon
ReScript JSON Typed Strongly
Favicon
使用序列化在兩個 Rails 站台間傳遞物件
Favicon
Serialização no Kotlin
Favicon
Working with Firebase Cloud Firestore made easier with "withConverter()"
Favicon
Meet Model Object Mapper, a Database Serialization Utility for Django!
Favicon
How to Speak Binary in TypeScript
Favicon
Practical Java 16 - Using Jackson to serialize Records

Featured ones: