Markdown 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
- ✓Markdown Parser runs in O(n) time and O(n) space, in TypeScript as in every other language.
- ✓Runtime behaviour is unchanged; what the type layer buys is a closed node set. The mdast shapes used across the remark ecosystem are published as @types/mdast, where Root, Paragraph, Emphasis, Strong, Link and LinkReference are separate interfaces sharing a literal type discriminant, and markdown-it has @types/markdown-it.
- ✓Brand the normalised label. Reference matching only works on a stripped, whitespace-collapsed, case-folded string, and a plain string parameter lets any caller hand over a raw one; declaring type Label = string & { readonly [brand]: 'md-label' } against a unique symbol makes refs.get(rawLabel) a compile error and emits nothing.
- ✓The TypeScript trap: Narrowing outlives the call that invalidates it. Delimiter stacks are doubly linked and the emphasis pass unlinks nodes through other references, so if (opener.next !== null) { removeBetween(opener, closer); return opener.next.length; } typechecks cleanly: the checker does not reset a property's narrowed type because some other function mutated that property.
- ✓Types erase, so the AST modelling costs one thing at runtime: the discriminant. A switch over string literals compiles to sequential comparisons rather than a jump table, so order the frequent kinds first or intern the tags as numbers.
What Markdown Parser actually is
Markdown Parser in TypeScript: what you actually reach for
TypeScript implementation
type Inline =
| { readonly kind: "text"; readonly value: string }
| { readonly kind: "emph"; readonly children: readonly Inline[] }
| { readonly kind: "strong"; readonly children: readonly Inline[] }
| { readonly kind: "link"; readonly dest: string; readonly children: readonly Inline[] };
declare const brand: unique symbol;
/** A label already stripped, whitespace-collapsed and case-folded. */
type Label = string & { readonly [brand]: "md-label" };
function normalizeLabel(raw: string): Label {
return raw.trim().replace(/[ \t\r\n]+/g, " ").toLowerCase() as Label;
}
type RefMap = ReadonlyMap<Label, { readonly dest: string }>;
function renderInline(node: Inline): string {
switch (node.kind) {
case "text":
return node.value;
case "emph":
return "<em>" + node.children.map(renderInline).join("") + "</em>";
case "strong":
return "<strong>" + node.children.map(renderInline).join("") + "</strong>";
case "link":
return '<a href="' + node.dest + '">' + node.children.map(renderInline).join("") + "</a>";
default:
return unreachable(node); // a new node kind turns this line into an error
}
}
function unreachable(x: never): never {
throw new Error("unhandled inline: " + JSON.stringify(x));
}
/** refs.get(rawLabel) does not compile: the key type is branded. */
function referenceLink(refs: RefMap, label: string, kids: readonly Inline[]): Inline {
const hit = refs.get(normalizeLabel(label));
return hit === undefined
? { kind: "text", value: "[" + label + "]" }
: { kind: "link", dest: hit.dest, children: kids };
}
export { renderInline, normalizeLabel, referenceLink };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 Markdown Parser?
Runtime behaviour is unchanged; what the type layer buys is a closed node set. The mdast shapes used across the remark ecosystem are published as @types/mdast, where Root, Paragraph, Emphasis, Strong, Link and LinkReference are separate interfaces sharing a literal type discriminant, and markdown-it has @types/markdown-it. Modelling your own inline AST the same way, as a union discriminated on a kind field, is what makes the renderer exhaustive: the default branch passes the value to a function taking never, so adding a node kind becomes a compile error everywhere that forgot it.
What is the most common TypeScript mistake when implementing Markdown Parser?
Narrowing outlives the call that invalidates it. Delimiter stacks are doubly linked and the emphasis pass unlinks nodes through other references, so if (opener.next !== null) { removeBetween(opener, closer); return opener.next.length; } typechecks cleanly: the checker does not reset a property's narrowed type because some other function mutated that property. Compiled under strict and run, that shape throws TypeError: Cannot read properties of null (reading 'length'). Copy the value into a const before the call, or make the links readonly and rebuild, since only assignments the checker can see discard the narrowing.
How does Markdown Parser actually perform in TypeScript?
Types erase, so the AST modelling costs one thing at runtime: the discriminant. A switch over string literals compiles to sequential comparisons rather than a jump table, so order the frequent kinds first or intern the tags as numbers. enum emits a real object plus a reverse-mapping entry; const enum inlines within a single compile but, when imported across files under isolatedModules (the flag most bundlers now require), tsc still passes it clean while single-file transpilers like esbuild/swc cannot inline a value from a file they never look inside, the import silently survives into the output with the enum member never defined at runtime, a broken build rather than a compile error. The other cost is at build time, where a deeply recursive union of thirty node interfaces makes the checker renormalise on every children access, and that is what makes tsc crawl. 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 full price for a tool, check the student deals on AI and developer tools listed 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.