Base64 Encoding in TypeScript

TypeScript provides built-in support for base64 encoding/decoding through the btoa and atob functions in the global scope.

// This function converts a string to a Uint8Array
function stringToUint8Array(str: string): Uint8Array {
    return new TextEncoder().encode(str);
}

// This function converts a Uint8Array to a string
function uint8ArrayToString(array: Uint8Array): string {
    return new TextDecoder().decode(array);
}

// Here's the string we'll encode/decode
const data: string = "abc123!?$*&()'-=@~";

// TypeScript supports base64 encoding through the btoa function
// btoa requires a string input
const sEnc: string = btoa(data);
console.log(sEnc);

// Decoding is done using the atob function
// It returns a string, so we don't need to convert it
const sDec: string = atob(sEnc);
console.log(sDec);
console.log();

// For URL-compatible base64, we need to replace some characters
function toUrlSafeBase64(base64: string): string {
    return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
}

function fromUrlSafeBase64(urlSafeBase64: string): string {
    return urlSafeBase64.replace(/-/g, '+').replace(/_/g, '/');
}

// This encodes/decodes using a URL-compatible base64 format
const uEnc: string = toUrlSafeBase64(btoa(data));
console.log(uEnc);
const uDec: string = atob(fromUrlSafeBase64(uEnc));
console.log(uDec);

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.

To run this TypeScript code, you would typically compile it to JavaScript and then run it with Node.js. Here’s an example of how you might do that:

$ tsc base64-encoding.ts
$ node base64-encoding.js
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

Note that TypeScript doesn’t have built-in URL-safe base64 encoding, so we’ve implemented simple functions to convert between standard and URL-safe base64. In a real-world scenario, you might want to use a library that provides more robust implementations of these functions.