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

后端 未结 4 2204
花落未央
花落未央 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:40

    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.

提交回复
热议问题