Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
Open
Description
In TypeScript it's possible to use a class as a type/interface, as documented in theHandbook. I'm sure that there is use case for this, but in general this leads to unpredictable behaviour.
For example, take the following class:
classPoint{publicx:number;publicy:number;constructor(x:number,y:number){if(x<0||y<0){thrownewError('Point must have positive values');}this.x=x;this.y=y;}}
This constructor makes sure thatx
andy
cannot be negative values, however the following is allowed:
constmyPoint:Point={x:-1,y:-2};
This type of construction also breaksinstanceof
checks:
constrealPoint=newPoint(1,2);console.log(realPointinstanceofPoint);// => trueconstfakePoint:Point={x:1,y:2};console.log(fakePointinstanceofPoint);// => false
Constructors 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.