Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'items' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer

I just started learning coding and I just couldn't understand how to fix this.

This is the error:

'items' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.

export class Model 
{
    user;
    items;

   constructor()  
   {
       this.user = "User";
       this.items = [
       
         new TodoItems("Sports", false),
         new TodoItems("Breakfast", false),
         new TodoItems("Reading Books", false),
         new TodoItems("Cinema", false),
       ];
   }
}
like image 900
lowint Avatar asked Jan 31 '26 01:01

lowint


1 Answers

The issue here is that you do not define any type for the items field. So by default is considered to be of type any. And it looks like TypeScript has an issue inferring the array type when you assign directly to the non typed field in the constructor.

There are two possibilities to work around this problem. The first is to assign the value directly to the field on declaration.

export class Model 
{
    user;
    items = [
       
         new TodoItems("Sports", false),
         new TodoItems("Breakfast", false),
         new TodoItems("Reading Books", false),
         new TodoItems("Cinema", false),
       ];

   constructor()  
   {
       this.user = "User";
   }
}

The other option is to first assign the array to a local variable that gets correct type and then assign to the field.

export class Model
{
    user;
    items;

   constructor()  
   {
       this.user = "User";
       const items = [
         new TodoItems("Sports", false),
         new TodoItems("Breakfast", false),
         new TodoItems("Reading Books", false),
         new TodoItems("Cinema", false),
       ];
       this.items = items;
   }
}

In my opinion it is better to assign the values directly to fields when you define them if you want to automatically infer types especially since you are just assigning constant values so there is no need to do it in the constructor. Else I think you should define the type for the fields when you define them and then you will not have this issue.

like image 181
AlesD Avatar answered Feb 01 '26 19:02

AlesD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!