How to Speak Binary in TypeScript

1 min read Original article ↗

Andrew Morris

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

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:

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:

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 }

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 😉.