Invalid Constructor Usage
ID |
javascript.invalid_constructor_usage |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
classes, reliability, runtime-error |
Description
Reports a new X() expression whose target is a function that cannot be used as a constructor at runtime:
const fn = () => ({ x: 1 });
const obj = new fn(); // FLAW — TypeError at runtime
async function load() { ... }
const r = new load(); // FLAW — async functions are not constructors
function* gen() { yield 1; }
const g = new gen(); // FLAW — generators are not constructors
Rationale
The JavaScript runtime distinguishes between functions that can be invoked with new and those that cannot:
In every case the call throws a TypeError. The rule catches the bug at static analysis time, before it surfaces as a runtime exception in production.
Remediation
Use the function as a regular call, or change the declaration to a normal function or class if construction is the intent:
const obj = fn();
class Foo { ... }
const obj = new Foo();