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




Asked on May 13, 2023
I have a component in my Angular application.

@Component({
  ......
})
export class AddWriterComponent {
    writerName: string;
    books: Book[];
    constructor() {

    }
    ......
}
 I am getting error for "writerName" as

Property 'writerName' has no initializer and is not definitely assigned in the constructor.ts(2564)

Error for "books":

Property 'books' has no initializer and is not definitely assigned in the constructor.ts(2564)

How to fix it?



Replied on May 13, 2023
You are getting this error because of recent TypeScript changes.

“TypeScript 2.7 introduces a new flag called strictPropertyInitialization. This flag performs checks to ensure that each instance property of a class gets initialized in the constructor body, or by a property initializer.”
 
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html

If we don’t initialize, we get the error “Property has no initializer and is not definitely assigned in the constructor”

We can resolve the error either by property initialization or disabling strict property initialization in tsconfig.json or making property initialization optional.


Find the possible ways to fix the issue.

(A). Initialize the property. It is good practice to initialize the properties to avoid the null value error in our application.

1.

writerName= {} as string;
books= {} as Book[];

2.  

writerName: string = '';
books: Book[] = [];

(B). Initialize the property in constructor.

1.

writerName: string;
books: Book[];
constructor(writerName: string, books: Book[]) {
      this.writerName = writerName;
      this.books = books;
}

2.

writerName: string;
books: Book[];
constructor(writerName: string, books: Book[]) {
      this.writerName = writerName ?? '';
      this.books = books?? [];
}

3.

writerName: string;
books: Book[];
constructor() {
  this.writerName = "";
  this.books= [];
}

(C) Make initialization optional using signs (?) Or (!) Or undefined keyword.

1.

writerName?: string;
books?: Book[];

2.

writerName!: string;
books!: Book[];

3.
writerName: string | undefined;
books: Book[] | undefined;


(D). Go to tsconfig.json, change the value of strict to false.

"compilerOptions": {
  "strict": false,
  ------
}




Write Answer









©2024 concretepage.com | Privacy Policy | Contact Us