Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Trie Autocomplete Implementation in TypeScript

14 min readintermediate
Website QA and SEO audits

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

  • ✓Trie Autocomplete runs in O(m) time and O(n*m) space, in TypeScript as in every other language.
  • ✓The runtime is JavaScript, so the container is still Map<string, TrieNode>. What TypeScript adds is that Map.prototype.get is typed as TrieNode | undefined, which forces the miss branch to exist.
  • ✓Reviewers reject the non-null assertion operator on child lookups: node.children.get(ch)! is exactly the place where the runtime miss happens.
  • ✓The TypeScript trap: noUncheckedIndexedAccess is off by default. With children typed as Record<string, TrieNode>, the expression node.children[ch] has type TrieNode, never TrieNode | undefined, so node = node.children[ch] compiles cleanly and then throws Cannot read properties of undefined on the first prefix that is not in the dictionary.
  • ✓Types are erased, so there is no TypeScript runtime cost at all and every JavaScript engine note applies unchanged.

What Trie Autocomplete actually is

A trie stores a set of strings as a tree where each edge carries one character and every node is the shared prefix of everything beneath it. Walking m characters lands you on the subtree of all completions, so prefix lookup costs O(m) regardless of dictionary size; enumerating k suggestions then costs O(k) plus the length of what you emit. Engineers reach for it for search-box typeahead, command palettes, IP/route tables and spell correction: anywhere the query is a prefix and the answer set must be produced per keystroke. If the dictionary is static and read-only, a sorted array plus binary search is usually smaller and faster.

Trie Autocomplete in TypeScript: what you actually reach for

The runtime is JavaScript, so the container is still Map<string, TrieNode>. What TypeScript adds is that Map.prototype.get is typed as TrieNode | undefined, which forces the miss branch to exist. A recursive interface is legal and is the idiomatic node shape: interface TrieNode { readonly children: Map<string, TrieNode>; isWord: boolean }. There is no char type, so the key stays string. Record<string, TrieNode> and index signatures are the trap described below. mnemonist ships its own .d.ts; @types is not needed for it.

TypeScript implementation

Reviewers reject the non-null assertion operator on child lookups: node.children.get(ch)! is exactly the place where the runtime miss happens. They want a local const next = node.children.get(ch); if (!next) return []; so control flow narrows the type. children is marked readonly on the interface (the Map is mutated, the field is not reassigned). The traversal variable is declared let node: TrieNode | undefined so reassignment from .get() typechecks without a cast.
typescript
interface TrieNode {
  readonly children: Map<string, TrieNode>;
  isWord: boolean;
}

const newNode = (): TrieNode => ({ children: new Map(), isWord: false });

export class Trie {
  private readonly root: TrieNode = newNode();

  insert(word: string): void {
    let node = this.root;
    for (const ch of word) {
      let next = node.children.get(ch);
      if (!next) {
        next = newNode();
        node.children.set(ch, next);
      }
      node = next;
    }
    node.isWord = true;
  }

  complete(prefix: string, limit = 10): string[] {
    let node: TrieNode | undefined = this.root;
    for (const ch of prefix) {
      node = node.children.get(ch);
      if (!node) return [];
    }
    const out: string[] = [];
    const stack: Array<[TrieNode, string]> = [[node, prefix]];
    while (out.length < limit) {
      const top = stack.pop();
      if (!top) break;
      const [n, path] = top;
      if (n.isWord) out.push(path);
      const keys = [...n.children.keys()].sort().reverse();
      for (const ch of keys) {
        const child = n.children.get(ch);
        if (child) stack.push([child, path + ch]);
      }
    }
    return out;
  }
}

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 Free

The TypeScript-specific trap

noUncheckedIndexedAccess is off by default. With children typed as Record<string, TrieNode>, the expression node.children[ch] has type TrieNode, never TrieNode | undefined, so node = node.children[ch] compiles cleanly and then throws Cannot read properties of undefined on the first prefix that is not in the dictionary. The compiler told you it was safe and it was not. Second, TypeScript-only: with target ES5 and downlevelIteration off, for (const ch of word) is emitted as an index loop over UTF-16 code units, so the same source splits astral characters after transpilation and not before.

Performance in TypeScript, beyond the O(m)

Types are erased, so there is no TypeScript runtime cost at all and every JavaScript engine note applies unchanged. The shape story is decided by how you build the node, not by whether you typed it: a single factory, one object-literal site with a fixed key set and a fixed key order like the newNode below, walks one transition chain and is as monomorphic as a class constructor. What actually costs you is scattering literals with different key orders across the file, or adding isWord after the fact; declaring the node as a class is the easy way to make that impossible. And downlevel emit matters: transpiling for...of and spread to ES5 helpers adds an array allocation per level of the walk that the ES2015+ target does not. The asymptotic cost is the same in every language, O(m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Trie Autocomplete between languages.

Real-World Applications

Trie Autocomplete applies wherever its problem shape appears in your own code. In TypeScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Trie Autocomplete helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Trie Autocomplete appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Trie Autocomplete over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Trie Autocomplete to build pattern recognition. In TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

Frequently Asked Questions

Which TypeScript type or library should I use for Trie Autocomplete?

The runtime is JavaScript, so the container is still Map<string, TrieNode>. What TypeScript adds is that Map.prototype.get is typed as TrieNode | undefined, which forces the miss branch to exist. A recursive interface is legal and is the idiomatic node shape: interface TrieNode { readonly children: Map<string, TrieNode>; isWord: boolean }. There is no char type, so the key stays string. Record<string, TrieNode> and index signatures are the trap described below. mnemonist ships its own .d.ts; @types is not needed for it.

What is the most common TypeScript mistake when implementing Trie Autocomplete?

noUncheckedIndexedAccess is off by default. With children typed as Record<string, TrieNode>, the expression node.children[ch] has type TrieNode, never TrieNode | undefined, so node = node.children[ch] compiles cleanly and then throws Cannot read properties of undefined on the first prefix that is not in the dictionary. The compiler told you it was safe and it was not. Second, TypeScript-only: with target ES5 and downlevelIteration off, for (const ch of word) is emitted as an index loop over UTF-16 code units, so the same source splits astral characters after transpilation and not before.

How does Trie Autocomplete actually perform in TypeScript?

Types are erased, so there is no TypeScript runtime cost at all and every JavaScript engine note applies unchanged. The shape story is decided by how you build the node, not by whether you typed it: a single factory, one object-literal site with a fixed key set and a fixed key order like the newNode below, walks one transition chain and is as monomorphic as a class constructor. What actually costs you is scattering literals with different key orders across the file, or adding isWord after the fact; declaring the node as a class is the easy way to make that impossible. And downlevel emit matters: transpiling for...of and spread to ES5 helpers adds an array allocation per level of the walk that the ES2015+ target does not. Time complexity is O(m) and space is O(n*m).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

If you are a student, see what Replit offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.