diff-match-patch-typescript
diff-match-patch-typescript is a direct, strongly-typed TypeScript port of Google's `diff-match-patch` library. It provides robust algorithms for computing differences between two texts, finding approximate string matches, and applying patches. This package, currently at version 1.1.3, aims for full functional parity with the original Java/JavaScript implementation, ensuring that developers leveraging TypeScript benefit from type safety and modern tooling while utilizing a widely-used and proven diffing solution. It's actively maintained with continuous integration, making it a reliable choice for text manipulation tasks where precise diffing, matching, and patching are required. Its core differentiators include its faithfulness to the original algorithm and its full TypeScript support.
Common errors
-
TypeError: dmp.diff_main is not a function
cause The `DiffMatchPatch` class was either not correctly imported or not instantiated before calling its methods.fixEnsure you use `import { DiffMatchPatch } from 'diff-match-patch-typescript';` and then create an instance with `const dmp = new DiffMatchPatch();` before attempting to call methods like `dmp.diff_main`. -
ReferenceError: DiffOperation is not defined
cause The `DiffOperation` enum was used without being explicitly imported from the package.fixAdd `DiffOperation` to your import statement: `import { DiffMatchPatch, DiffOperation } from 'diff-match-patch-typescript';`. -
TS2345: Argument of type 'number' is not assignable to parameter of type 'DiffOperation'
cause Attempting to manually assign or compare diff operation results using magic numbers (0, 1, -1) instead of the `DiffOperation` enum members.fixAlways use the `DiffOperation` enum for clarity and type safety: `if (op[0] === DiffOperation.DIFF_EQUAL) { ... }` instead of `if (op[0] === 0) { ... }`.
Warnings
- gotcha The `diff-match-patch` algorithm (and thus this port) uses configurable parameters like `diffTimeout` and `diffEditCost` that significantly affect diff accuracy and performance. Default values might not be optimal for all use cases, particularly very long texts or highly dissimilar strings, potentially leading to 'suboptimal' diffs if not tuned.
- gotcha As a direct port, this library replicates the behavior of the original Google `diff-match-patch`, which was developed primarily for browser environments and may have nuances or performance characteristics that differ from more modern or specialized Node.js diffing libraries.
- deprecated While still functional, the original `google/diff-match-patch` library has not seen significant updates in many years. While this TypeScript port provides modern language benefits, the underlying algorithm itself is mature and not actively evolving. Developers might want to evaluate newer diffing algorithms for specific cutting-edge use cases.
Install
-
npm install diff-match-patch-typescript -
yarn add diff-match-patch-typescript -
pnpm add diff-match-patch-typescript
Imports
- DiffMatchPatch
const DiffMatchPatch = require('diff-match-patch-typescript').DiffMatchPatch;import { DiffMatchPatch } from 'diff-match-patch-typescript'; - DiffOperation
const { DiffOperation } = require('diff-match-patch-typescript');import { DiffOperation } from 'diff-match-patch-typescript'; - default import (class)
import DiffMatchPatch from 'diff-match-patch-typescript';
import { DiffMatchPatch } from 'diff-match-patch-typescript';
Quickstart
import { DiffMatchPatch, DiffOperation } from 'diff-match-patch-typescript';
const dmp = new DiffMatchPatch();
// Example 1: Compute a diff between two strings
const text1 = 'The quick brown fox jumps over the lazy dog.';
const text2 = 'A quick brown cat jumps over the agile fox.';
console.log('--- Diff Example ---');
const diffs = dmp.diff_main(text1, text2);
console.log('Diff result:', JSON.stringify(diffs));
// Expected output: array of [operation, text] tuples
// e.g., [[-1,"The"],[1,"A"],[0," quick brown "],[-1,"fox"],[1,"cat"],[0," jumps over the "]...]
// Example 2: Find a match within a text
const mainText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
const pattern = 'consectetur';
const startIndex = 0;
console.log('\n--- Match Example ---');
const position = dmp.match_main(mainText, pattern, startIndex);
console.log(`Pattern '${pattern}' found at position: ${position}`);
// Expected output: 28 (index of 'c' in 'consectetur')
// Example 3: Apply a patch to a text
const originalText = 'Hello World';
const newDesiredText = 'Hello TypeScript';
console.log('\n--- Patch Example ---');
const patches = dmp.patch_make(originalText, newDesiredText);
console.log('Generated patches:', JSON.stringify(patches));
const [patchedText, results] = dmp.patch_apply(patches, originalText);
console.log(`Original: '${originalText}', Patched: '${patchedText}', Success: ${results[0]}`);
// Expected output: newText: "Hello TypeScript", results: [true]