TypeScript complain "has no initializer and is not definitely assigned in the constructor" about constructors by returning constructed object

66,822

Solution 1

strictPropertyInitialization forces you to initialize all properties that are not optional in the constructor of the class. This check can be useful as it ensures that you don't get unexpected uninitialized properties. There are several ways to get around the error, the first two are the general way to do it, in your case only the last on applies (I include all for completeness):

Initialize the field

If you define the property as boolean if should be true or false initialize it when you declare the field or initialize it in the constructor:

class MyClass {
  someField: boolean = false;
  constructor() {
    return { someField: true };
  }
}

Make the field optional

If the field can be undefined, you should mark this in the field declaration either by using ? or typing the field as undefined|boolean

class MyClass {
    //someField?: boolean;
    someField: boolean | undefined;
    constructor() {
        return { someField: true };
    }
}

Use a not null assertion

In your case since in the constructor you are actually not initializing the current object (this) but returning a new one, you can tell the compiler it is wrong about the error and use a not null assertion. This assertion is specifically introduced because there are limitations in strictPropertyInitialization checks and sometimes the compiler gets it wrong. For those cases you can override what the compiler thinks, but you have to be explicit about it:

class MyClass {
    someField!: boolean;
    constructor() {
        return { someField: true };
    }
}

Solution 2

Solution 1

Add (!) sign after name:

someField!:string;

Solution 2

Open TypeScript config file tsconfig.json and add this code to compiler options

 "angularCompilerOptions": {
    //   ...
    "strictPropertyInitialization": false
    //   ...
  }

Note: it will make static analysis weaker

Solution 3

"angularCompilerOptions": {
    //   ...
    "strictPropertyInitialization": false
    //   ...   }

According to angular latest version, it supports strict typing, so you have to disable it.

Make modifications and restart server

Solution 4

It considers {someField: true} as new object and the property someField has not been initialized.What is the purpose of return inside the constructor? You can replace it with this.someField = true.

Edit: Actually, I debugged for more info, Try adding "strictPropertyInitialization": false to your compiler options and check. But it overrules the type strictness(beautiful feature of TS). But In my opinion, do not do this. For more info.

Solution 5

When you face the same error while declaring variable of type string you can solve the issue by initializing it as an empty string.

public myString: string= ' ';

also you can use keyword undefined:

public myString: string | undefined;

If its an array you can use ! immediately after variable name,

public myArray!: arrayName[];
Share:
66,822

Related videos on Youtube

tsh
Author by

tsh

:)

Updated on February 03, 2022

Comments

  • tsh
    tsh over 2 years

    TypeScript show following error message to this code samples:

    class MyClass {
      someField: boolean;
      constructor() {
        return { someField: true };
      }
    }
    

    Property 'someField' has no initializer and is not definitely assigned in the constructor.


    (property) MyClass.someField: boolean

    TypeScript Playground (You need to enable strictNullChecks and strictPropertyInitialization to see this error message.)

    Given code snippet is simplified from my original script. I would like to return the constructed value instead of assign values to this in constructor. What should I do to make TypeScript works without mentioned error?

    • Ian Kemp
      Ian Kemp over 5 years
      Your code makes no sense. Why would you try to return a value from a constructor? Why would you try to return a value that isn't an instance of the class?
    • tsh
      tsh over 5 years
      @IanKemp return in constructor is perfect valid (at least in JavaScript). And I would consider TypeScript as superset of JavaScript. So why it makes no sense. You may get more information about how to write a JavaScript constructor from MDN.
    • Ian Kemp
      Ian Kemp over 5 years
      But this isn't vanilla JavaScript, it's Typescript, and one of the reasons TS exists is to prevent you from doing some of the weird and nonsensical things that JavaScript allows, and returning a non-this value from a constructor definitely falls under "weird and nonsensical". If you're going to write JS in TS, just write JS!
  • tsh
    tsh over 5 years
    You may get more information about how return value in constructor worked in JavaScript from MDN. I would consider TypeScript as superset of JavaScript. And to my understanding, this means I can do this and it should work as is.
  • Namrata Das
    Namrata Das over 3 years
    This might still break instanceof though
  • npup
    npup over 3 years
    the question has nothing to do with angular, nor is any "server" involved
  • npup
    npup over 3 years
    Kindly check your own answer and realize that just over 5% of the words in your sentence under the code consists of the word "server". This answer will get no votes besides downvotes I am afraid.
  • DineshKP
    DineshKP about 3 years
    Strongly advise against disabling strict checks. These were introduced for a reason. I suggest we read and learn to the reason why they were introduced and play along with the rules. It will help you develop better software