Jean-Philippe Dufour
Jean-Philippe Dufour

Reputation: 151

TypeScript Setter Compile error but it still does its job?

Typescript 3.0.1 gives me a compiling error for my setter inside my class but it still does it's job as it should when I run my JS as you can see on the picture.

Code looks like this :

enter image description here

Is there a reason for that? How do I get it to compile without the error because it is confusing me as I am learning Typescript.

Upvotes: 0

Views: 104

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30899

When a property such as X is defined by accessors, the return type of the get accessor must be the same as the parameter type of the set accessor. Since you didn't annotate either type, by default TypeScript uses the type actually returned by the get accessor, which is the type of the property x declared in the constructor, which is number | undefined because x was declared optional. Thus, in the set accessor, the type of value is number | undefined, and TypeScript won't let you compare value <= 0 if value can be undefined.

To fix the problem, either change the type of x so it doesn't include undefined (e.g., by specifying a default value for the x parameter in the constructor) or check for value being undefined in the set accessor.

Upvotes: 1

Related Questions