Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Readonly property has no initializer and is not definitely assigned in the constructor

Creating a class like:

class myProps {
  public readonly val1: boolean;

  constructor(val1?: boolean) {
    val1 != undefined ? this.val1 = val1 : val1 = true;
  }
}

I would expect that his is ok, as inside the constructor (unlike the error claims) val1 is always set to a value. however I get this error (inside the IDE) on the readonly attribute val1:

Property ‘val1’ has no initializer and is not definitely assigned in
the constructor.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why is this and how would I fix it correctly?

>Solution :

You are missing a this before your second assignment of val1, so you’re assigning to the local variable in the other branch, not the instance variable, hence the error that it is not always initialized. It should be

class myProps {
  public readonly val1: boolean;

  constructor(val1?: boolean) {
    val1 != undefined ? this.val1 = val1 : this.val1 = true;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading