XML Parser 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
- ✓XML Parser runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓The DOM library declarations describe DOMParser, Document and Element, but only when the DOM library is included in the compiler options.
- ✓Return a discriminated union from the parse wrapper, an ok variant carrying the document and an error variant carrying the message, so the parsererror check cannot be skipped without a compiler error.
- ✓The TypeScript trap: The DOM types are honest about nullability in ways people route around rather than handle: querySelector returns Element or null, and textContent is string or null even on an element that exists, so reading a value out of a document involves two separate null checks that the optional-chaining operator collapses into a silent undefined.
- ✓Erased at compile time; the runtime is whichever parser the platform provides. The discriminated union costs one tag check per parse.
What XML Parser actually is
XML Parser in TypeScript: what you actually reach for
TypeScript implementation
// Requires "DOM" in tsconfig "lib". A default Node project does NOT
// include it, so this same file fails to compile server-side.
type ParseResult =
| { readonly ok: true; readonly doc: Document }
| { readonly ok: false; readonly message: string };
/** The union makes the parsererror check impossible to forget. */
export function parseXml(source: string): ParseResult {
const doc = new DOMParser().parseFromString(source, 'application/xml');
const error = doc.querySelector('parsererror');
if (error !== null) {
return { ok: false, message: error.textContent?.trim() ?? 'malformed XML' };
}
return { ok: true, doc };
}
interface Order {
id: string;
total: number;
}
export function readOrders(source: string): Order[] {
const result = parseXml(source);
if (!result.ok) {
throw new SyntaxError(result.message); // the compiler forced this branch
}
const orders: Order[] = [];
for (const el of Array.from(result.doc.querySelectorAll('order'))) {
const id = el.getAttribute('id'); // string | null
const totalText = el.querySelector('total')?.textContent; // string | null | undefined
if (id === null || totalText == null) continue; // handle, do not ?? away
const total = Number(totalText);
if (!Number.isFinite(total)) continue;
orders.push({ id, total });
}
return orders;
}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 XML Parser?
The DOM library declarations describe DOMParser, Document and Element, but only when the DOM library is included in the compiler options. A default Node project does not include it, so the same source compiles in a browser package and fails in a server one.
What is the most common TypeScript mistake when implementing XML Parser?
The DOM types are honest about nullability in ways people route around rather than handle: querySelector returns Element or null, and textContent is string or null even on an element that exists, so reading a value out of a document involves two separate null checks that the optional-chaining operator collapses into a silent undefined. That is convenient and it is exactly how a missing field becomes an empty string three layers away. The configuration issue compounds it, because whether these types exist at all depends on the lib setting rather than on the code, so a shared parsing utility can type-check in one package of a monorepo and not in another.
How does XML Parser actually perform in TypeScript?
Erased at compile time; the runtime is whichever parser the platform provides. The discriminated union costs one tag check per parse. 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 trialBefore paying for Replit, check its student and free-tier options 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.