31

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?

3
  • 5
    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?
    – Ian Kemp
    Commented Jan 9, 2019 at 7:09
  • 2
    @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.
    – tsh
    Commented Jan 9, 2019 at 7:22
  • 6
    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!
    – Ian Kemp
    Commented Jan 9, 2019 at 7:31

5 Answers 5

69

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 };
    }
}
1
  • This might still break instanceof though
    – Evert
    Commented Dec 31, 2020 at 9:11
20

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

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

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

Make modifications and restart server

3
  • 3
    the question has nothing to do with angular, nor is any "server" involved
    – npup
    Commented Jan 7, 2021 at 12:45
  • 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.
    – npup
    Commented Jan 21, 2021 at 21:34
  • 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
    – DineshKP
    Commented Jun 16, 2021 at 11:22
2

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.

1
  • 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.
    – tsh
    Commented Jan 9, 2019 at 7:23
0

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[];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.