Rule proposal: disallow object assignment to constructed types
Author: d-lukCreated Oct 26, 2020Updated Sep 16, 2026
Labelspackage: eslint-pluginenhancement: new plugin ruleaccepting prs
In TypeScript it's possible to use a class as a type/interface, as documented in the Handbook. I'm sure that there is use case for this, but in general this leads to unpredictable behaviour.
For example, take the following class:
class Point {
public x: number;
public y: number;
constructor(x: number, y: number) {
if (x < 0 || y < 0) {
throw new Error('Point must have positive values');
}
this.x = x;
this.y = y;
}
}This constructor makes sure that x and y cannot be negative values, however the following is allowed:
const myPoint: Point = { x: -1, y: -2 };This type of construction also breaks instanceof checks:
const realPoint = new Point(1, 2);
console.log(realPoint instanceof Point); // => true
const fakePoint: Point = { x: 1, y: 2 };
console.log(fakePoint instanceof Point); // => falseConstructors are used to assert proper object instantiation. Therefore, allowing it to be circumvented can lead to bugs.
Proposed solution
Add a rule that enforces calling the constructor when initializing a class.
Source: typescript-eslint/typescript-eslint