{"record":{"id":"cdfb28ee57bb3e2d","repo":"trekhleb/javascript-algorithms","slug":"cannot-construct-heap-instance-directly","errorCode":null,"errorMessage":"Cannot construct Heap instance directly","messagePattern":"Cannot construct Heap instance directly","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"src/data-structures/heap/Heap.js","lineNumber":13,"sourceCode":"import Comparator from '../../utils/comparator/Comparator';\n\n/**\n * Parent class for Min and Max Heaps.\n */\nexport default class Heap {\n  /**\n   * @constructs Heap\n   * @param {Function} [comparatorFunction]\n   */\n  constructor(comparatorFunction) {\n    if (new.target === Heap) {\n      throw new TypeError('Cannot construct Heap instance directly');\n    }\n\n    // Array representation of the heap.\n    this.heapContainer = [];\n    this.compare = new Comparator(comparatorFunction);\n  }\n\n  /**\n   * @param {number} parentIndex\n   * @return {number}\n   */\n  getLeftChildIndex(parentIndex) {\n    return (2 * parentIndex) + 1;\n  }\n\n  /**\n   * @param {number} parentIndex\n   * @return {number}","sourceCodeStart":1,"sourceCodeEnd":31,"githubUrl":"https://github.com/trekhleb/javascript-algorithms/blob/85293e3e2b88f4d2ce330d956b139cf628aa1e82/src/data-structures/heap/Heap.js#L1-L31","documentation":"Heap is an abstract base class for MinHeap and MaxHeap; its ordering hook pairIsInCorrectOrder() is deliberately unimplemented (it always throws, Heap.js:280-285), so a bare Heap could never order elements. The constructor guard `new.target === Heap` (Heap.js:12-14) makes that contract explicit by throwing a TypeError the instant new Heap(...) runs - the same pattern as abstract-class enforcement in other languages.","triggerScenarios":"new Heap() or new Heap((a, b) => a - b); a generic factory that receives the class by variable (new Ctor(cmp) where Ctor === Heap); importing Heap because it is the first hit when searching the package for 'heap'.","commonSituations":"Wanting 'just a heap' and instantiating the base class picked by an IDE auto-import; porting code from a library where Heap itself is concrete; factory code that defaults its class parameter to the base instead of a subclass.","solutions":["Instantiate a concrete subclass: new MinHeap(comparatorFunction) or new MaxHeap(comparatorFunction) - both accept an optional comparator, so custom ordering usually needs no subclass.","For truly custom ordering, extend Heap and implement pairIsInCorrectOrder(first, second) (return first <= second for a min-heap), then instantiate your subclass.","In a factory, default the class parameter to a concrete one: function makeHeap(Ctor = MinHeap) { return new Ctor(); }","Check imports: Heap should never appear after `new` outside its own subclasses."],"exampleFix":"// before\nimport Heap from './heap/Heap';\nconst heap = new Heap((a, b) => a - b); // TypeError: Cannot construct Heap instance directly\n\n// after\nimport MinHeap from './heap/MinHeap';\nconst heap = new MinHeap((a, b) => a - b);","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"import Heap from '../heap/Heap';\nimport MinHeap from '../heap/MinHeap';\nimport MaxHeap from '../heap/MaxHeap';\n\n// True only for constructors that may legally follow `new`\nconst isConcreteHeapClass = (Ctor) =>\n  Ctor === MinHeap || Ctor === MaxHeap || Ctor.prototype instanceof Heap;\n\nfunction makeHeap(Ctor = MinHeap, comparator) {\n  if (!isConcreteHeapClass(Ctor)) {\n    throw new TypeError('Heap subclasses only; Heap itself is abstract');\n  }\n  return new Ctor(comparator);\n}","tryCatchPattern":"try {\n  heap = new HeapClass(comparator);\n} catch (error) {\n  if (error instanceof TypeError && /Cannot construct Heap instance directly/.test(error.message)) {\n    heap = new MinHeap(comparator); // fall back to a concrete heap\n  } else {\n    throw error;\n  }\n}","preventionTips":["Never write `new Heap(...)` - use MinHeap/MaxHeap; both accept an optional comparatorFunction.","In TypeScript, declare `abstract class Heap` in a .d.ts so the compiler rejects direct construction.","Factories should default to a concrete subclass, never the base class.","When subclassing Heap, implement pairIsInCorrectOrder() immediately - it throws on first heapify otherwise."],"tags":["heap","abstract-class","instantiation","typeerror","priority-queue"],"backgroundTag":"abstract-class-instantiation","analyzedSha":"85293e3e2b88f4d2ce330d956b139cf628aa1e82","analyzedAt":"2026-08-24T05:59:10.417Z","schemaVersion":2},"datasetVersion":"2026-08-24T07:17:09.176Z"}