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

后端 未结 4 2144
花落未央
花落未央 2021-02-20 03:19

TypeScript show following error message to this code samples:

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


        
4条回答
  •  时光说笑
    2021-02-20 03:51

    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

提交回复
热议问题