logo hsb.horse
← Back to snippets index

Snippets

Uint8Array Helper Functions

A TypeScript wrapper to simplify new Uint8Array calls. Supports arrays, ArrayBuffers, and length-based initialization patterns.

Published: Updated:

When working with binary data in WebCrypto API and similar contexts, you end up calling new Uint8Array frequently. Writing the lengthy syntax every time gets tedious, so I created a wrapper for more concise usage.

Code

const BYTE_LENGTH = "byteLength";
export function toU8Array(length: number): Uint8Array;
export function toU8Array(
array: ArrayLike<number> | ArrayBufferLike
): Uint8Array;
export function toU8Array(
buffer: ArrayBufferLike,
byteOffset?: number,
length?: number
): Uint8Array;
export function toU8Array(
arg1: number | ArrayLike<number> | ArrayBufferLike,
arg2?: number,
arg3?: number
): Uint8Array {
return typeof arg1 === "number"
? new Uint8Array(arg1)
: BYTE_LENGTH in arg1
? new Uint8Array(arg1, arg2, arg3)
: new Uint8Array(arg1);
}

Usage Examples

Initialize with Specified Length

const arr = toU8Array(32);
// Uint8Array(32) [0, 0, 0, ...] - buffer for random values

Convert After Base64 Decoding

const base64 = "SGVsbG8gV29ybGQh";
const binary = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
const arr = toU8Array(binary);

Get Partial View of ArrayBuffer

const buffer = new ArrayBuffer(64);
const arr = toU8Array(buffer, 16, 16);
// view from byte 16, 16 elements

Implementation Notes

BYTE_LENGTH is defined as a constant to allow minification optimizations. The order of type guards matters: first check if it’s a number, then check for byteLength property to identify ArrayBufferLike, and treat everything else as ArrayLike.

Simple conversions work fine with new Uint8Array, but this wrapper shines when you want type-safe, unified interface handling.