1

variable x is defined & initialized by a method initNum which is called in the constructor but typescript keeps throwing an error:

Property 'x' has no initializer and is not definitely assigned in the constructor.(2564)

Edit: It is not supposed to throw an error because x is initialized. Is there a bug in the code or I'm supposed to add some rule to tsconfig?

Edit-2: This is different from this question: Property '...' has no initializer and is not definitely assigned in the constructor

1- It's not Angular 2- There's a clear initiation for x assigned directly to the constructor by a function. 3- It's synchronized.

class Point {
  x: number;

  constructor() {
    this.initNum()
    }

    initNum(){
    this.x = 0;
    }
}
Jalal
  • 3,308
  • 4
  • 35
  • 43
  • Well yes, Typescript gives you this error. What is the question? – kaya3 Feb 11 '21 at 00:51
  • Well, there's a `but`? do you suggest using `despite`? – Jalal Feb 11 '21 at 00:53
  • 1
    What question do you want an answer to? Are you asking for an explanation of why this error occurs, a way to suppress the error, a way of rewriting the code to avoid the error? – kaya3 Feb 11 '21 at 00:55
  • 1
    That the property might be assigned in some method the constructor is irrelevant. The language rules specify that the assignment has to be done _in the constructor itself_. This is, in part, so that the compiler isn't required to go following all the possible code paths to figure out if maybe the variable winds up assigned at some point or not. See also "Halting Problem", and of course the proposed duplicate. – Peter Duniho Feb 11 '21 at 01:06
  • Thanks for referring to another question which is another case. And I don't think this is related to `Halting Problem` because this also applies to `if` and it works correctly with conditions. – Jalal Feb 11 '21 at 01:13
  • 2
    It's not a question of the "Halting Problem" per-se, but there is some point where you have to make a cut when writing a typer. In this case (at this moment) TypeScript doesn't trace initialization across methods at all. It could later, but for now, just declare `x!: number` to let TS know that you really do initialize it. – Sean Vieira Feb 11 '21 at 02:37
  • Thanks, Sean. I already did this after reading about "Definite Assignment Assertions": https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#definite-assignment-assertions – Jalal Feb 11 '21 at 03:01
  • This error also appears when applying prototype variable to a class (for example: `Point.prototype.x = 0` which should be totally acceptable without value assignment in the constructor (that would beat the purpose of prototype variable). – mtx Apr 17 '22 at 20:43

0 Answers0