【问题标题】:'items' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer'items' 隐含类型为 'any',因为它没有类型注释并且在其自己的初始化程序中直接或间接引用
【发布时间】:2021-04-15 19:56:01
【问题描述】:

我刚开始学习编码,但我不明白如何解决这个问题。

这是错误:

'items' 隐式具有类型'any',因为它没有类型注释,并且在其自己的初始化程序中直接或间接引用。

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),
       ];
   }
}

【问题讨论】:

  • TypeScript 不知道数组的类型。它不关心,,偶然''你只在里面放了 ToDoItems 类型的对象。可以是其中的任何对象。要强制执行此声明,请声明类型:items: ToDoItems[]。用户是一个不同的故事,因为字符串/数字是原始类型,可以通过分配的值来推断。但最好显式设置一个类型。否则,您将不会收到类型不匹配的编译错误。

标签: angular typescript


【解决方案1】:

这里的问题是您没有为 items 字段定义任何类型。所以默认情况下被认为是any类型。当您直接分配给构造函数中的非类型化字段时,TypeScript 似乎在推断数组类型时存在问题。

有两种方法可以解决这个问题。第一种是直接将值赋给声明时的字段。

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";
   }
}

另一种选择是先将数组分配给获得正确类型的局部变量,然后再分配给字段。

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;
   }
}

在我看来,如果您想自动推断类型,最好在定义字段时直接将值分配给字段,特别是因为您只是分配常量值,因此无需在构造函数中执行此操作。否则我认为您应该在定义字段时定义字段的类型,然后您就不会遇到这个问题。

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 2019-01-01
    • 2017-06-16
    • 2021-09-27
    • 1970-01-01
    • 2020-09-25
    • 2018-10-29
    • 2019-08-04
    • 2020-03-06
    相关资源
    最近更新 更多