Base64 Encoding Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Base64 Encoding runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓TypeScript ships no runtime, only the declarations that decide which API you are allowed to name.
- ✓Reviewers push back on `type Base64 = string`, which buys nothing: use a branded type (`string & { readonly __brand: 'base64url' }`) so an unvalidated string cannot flow into a decoder.
- ✓The TypeScript trap: `Buffer` extends `Uint8Array`, so a function typed `(b: Uint8Array)` silently accepts one -- and the type erases two runtime behaviours it cannot express.
- ✓Nothing here costs runtime: types are erased and the emitted JS is whatever your target demands.
What Base64 Encoding actually is
Base64 Encoding in TypeScript: what you actually reach for
TypeScript implementation
import { Buffer } from "node:buffer";
export type Base64Url = string & { readonly __brand: "base64url" };
export function encode(bytes: Uint8Array): Base64Url {
// Buffer.from(Uint8Array) copies; Buffer.from(str) would re-encode as UTF-8
return Buffer.from(bytes).toString("base64url") as Base64Url;
}
export function decode(token: Base64Url): Uint8Array {
const buf = Buffer.from(token, "base64url");
// buf may be a view into Node's shared 8 KiB pool, so it must be copied out.
// new Uint8Array(bytes) copies AND yields a real Uint8Array; by contrast
// Uint8Array.prototype.slice.call(buf) copies but comes back as a Buffer via
// Symbol.species, so the declared return type would still be a lie.
return new Uint8Array(buf);
}
const t = encode(new TextEncoder().encode("Hello"));
// @ts-expect-error - a plain string is not a Base64Url
decode("aGVsbG8");
console.log(decode(t));
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Base64 Encoding?
TypeScript ships no runtime, only the declarations that decide which API you are allowed to name. `btoa`/`atob` are declared in `lib.dom.d.ts` AND, since @types/node v15.13/v14.17, as `@legacy` globals in `@types/node`'s `buffer.d.ts`. So they compile if your `lib` includes DOM or you have @types/node installed, and are a compile error only when you have neither -- which is why a `lib: ["ES2022"]` browser-free build can still surprise you by accepting them. `Buffer` comes from `@types/node` and is best imported explicitly as `import { Buffer } from "node:buffer"`. The encoding argument is the `BufferEncoding` union ('base64' | 'base64url' | ...), so a typo like 'base-64' is a compile error rather than a runtime throw.
What is the most common TypeScript mistake when implementing Base64 Encoding?
`Buffer` extends `Uint8Array`, so a function typed `(b: Uint8Array)` silently accepts one -- and the type erases two runtime behaviours it cannot express. First, a small `Buffer.from(str, 'base64')` is carved out of Node's shared 8 KiB pool, so `buf.buffer` is far larger than `buf` and `new Uint8Array(buf.buffer)` reads unrelated data. Second, `Buffer.prototype.slice` returns a VIEW while `Uint8Array.prototype.slice` copies, so the same call means different things depending on the runtime value behind the declared type.
How does Base64 Encoding actually perform in TypeScript?
Nothing here costs runtime: types are erased and the emitted JS is whatever your target demands. The real cost is structural: a `Uint8Array` boundary is only honest if you WRITE an explicit copy out of Node's Buffer pool, and that copy -- not the annotation -- is what a `Buffer`-typed API would have skipped. Recent lib definitions made typed arrays generic over their backing buffer, so `Uint8Array` now means `Uint8Array<ArrayBufferLike>` and will NOT flow into a parameter typed `Uint8Array<ArrayBuffer>` (the reverse direction is still fine) -- expect noisy signatures rather than slow code. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.