Levenshtein Distance 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
- ✓Levenshtein Distance runs in O(n*m) time and O(n*m) space, in TypeScript as in every other language.
- ✓The runtime is JavaScript, so nothing computes edit distance; types are all TypeScript adds.
- ✓Reviewers ask for readonly on the inputs and a single exported function, not a class with one static method.
- ✓The TypeScript trap: Enable noUncheckedIndexedAccess and every DP read becomes number | undefined, including Int32Array reads, because the flag applies to its numeric index signature and not only to plain arrays.
- ✓Types are erased, so the emitted loop is exactly the JavaScript one; TypeScript only costs you where it emits helpers.
What Levenshtein Distance actually is
Levenshtein Distance in TypeScript: what you actually reach for
TypeScript implementation
export function levenshtein<T>(
a: readonly T[],
b: readonly T[],
eq: (x: T, y: T) => boolean = (x, y) => x === y,
): number {
let x = a, y = b;
if (x.length < y.length) [x, y] = [y, x];
const m = y.length;
if (m === 0) return x.length;
let prev = new Int32Array(m + 1);
let cur = new Int32Array(m + 1);
for (let j = 0; j <= m; j++) prev[j] = j;
for (let i = 1; i <= x.length; i++) {
cur[0] = i;
const xi = x[i - 1] as T; // noUncheckedIndexedAccess widens this to T | undefined
for (let j = 1; j <= m; j++) {
const sub = prev[j - 1]! + (eq(xi, y[j - 1] as T) ? 0 : 1);
cur[j] = Math.min(prev[j]! + 1, cur[j - 1]! + 1, sub);
}
[prev, cur] = [cur, prev];
}
return prev[m]!;
}
export const distance = (a: string, b: string): number =>
levenshtein(Array.from(a), Array.from(b));
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*m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Levenshtein Distance?
The runtime is JavaScript, so nothing computes edit distance; types are all TypeScript adds. Int32Array is declared in lib.es5.d.ts with a numeric index signature. fastest-levenshtein and leven ship their own .d.ts, so check the package types/exports field before reaching for a @types/* install that may not exist. If the distance is part of an API contract, model it as a branded alias, type EditDistance = number & { readonly __brand: unique symbol }, rather than inventing a class; the value must stay a plain number at runtime.
What is the most common TypeScript mistake when implementing Levenshtein Distance?
Enable noUncheckedIndexedAccess and every DP read becomes number | undefined, including Int32Array reads, because the flag applies to its numeric index signature and not only to plain arrays. Math.min(prev[j] + 1, ...) stops compiling, and the reflex fix is a wall of non-null assertions. The accepted answer is to pay for the invariant once instead of asserting it per read: allocate both rows at m + 1 and check that width a single time above the loops, if (prev.length !== m + 1) throw new Error('row width'), so the three DP reads carry one documented ! each instead of silently absorbing an off-by-one in the row width. The other TypeScript-only trap is trying to compute the distance in the type system with recursive conditional types: the table is quadratic and the compiler gives up with 'Type instantiation is excessively deep and possibly infinite' after a handful of characters.
How does Levenshtein Distance actually perform in TypeScript?
Types are erased, so the emitted loop is exactly the JavaScript one; TypeScript only costs you where it emits helpers. Targeting ES5 turns [...a] into the __spreadArray helper, which assumes an array and copies it with slice; switch downlevelIteration on and it becomes __read, which walks the iterator protocol one step at a time and is markedly slower, so write Array.from explicitly and ship what you wrote. A regular enum emits a lookup object at runtime; const enum inlines but breaks under isolatedModules, so keep the substitution cost a plain number literal in the inner loop. Time complexity is O(n*m) and space is O(n*m).
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.