Debugging challengeIntermediate

The option that never arrived

Scenario

A topK utility takes an options object. One caller consistently gets the three *smallest* scores instead of the three largest — but only in one file. The options object is identical character-for-character to a working call elsewhere, except that it is built in a const first and passed by name. Everything compiles under strict: true. Explain what TypeScript checked, what it deliberately did not, and fix the API so the mistake cannot recur.

1interface TopKOptions {
2 k: number;
3 largest?: boolean; // default: false → ascending
4}
5
6function topK(nums: number[], options: TopKOptions): number[] {
7 const sorted = [...nums].sort((a, b) => a - b);
8 if (options.largest) sorted.reverse();
9 return sorted.slice(0, options.k);
10}
11
12const scores = [90, 12, 55, 98, 33, 70];
13
14// Inline literal: tsc catches the typo immediately —
15// topK(scores, { k: 3, largets: true });
16// error TS2353: Object literal may only specify known properties,
17// and 'largets' does not exist in type 'TopKOptions'.
18
19// The same object through a variable: compiles clean.
20const options = { k: 3, largets: true };
21console.log(topK(scores, options)); // [12, 33, 55] — expected [98, 90, 70]

Your task

  1. Why does the inline literal produce error TS2353 while the identical object passed through options compiles?
  2. What type does TypeScript infer for options, and why is that type assignable to TopKOptions even though it lacks largest and contains largets?
  3. Give three ways to make the variable-based call fail to compile (satisfies, an explicit annotation, an API change).
  4. The bug pattern generalises: two structurally identical types (say, an interval in seconds vs milliseconds) are interchangeable to the compiler. What is the idiom for making them incompatible?
  5. State the complexity of topK and name the structure that beats sorting when k is much smaller than n.
DebuggingEdge CasesSystematic Reasoning

Work it out

Write your analysis before revealing anything. The self-check below compares it against what a strong answer contains.

Reveal

Progressive — each section builds on the previous one.

The bug
Why it happens
The fix
Edge cases
Complexity

Self-check

Tick what your analysis covered. Be honest — this feeds your readiness profile.

0/6

Related concepts