【问题标题】:Error TS2741 ("property... is missing in type") being caused by the existence of a method由方法的存在引起的错误 TS2741(“类型中缺少属性...”)
【发布时间】:2021-08-26 17:08:01
【问题描述】:

我创建了以下示例代码以最小化重现我的问题:

class Test {
  prop1 : boolean
  prop2 : string

  method() { }

  static create(prop1 : boolean, prop2 : string) : Test {
    let item : Test = {
      prop1: prop1,
      prop2: prop2
    }

    return item;
  }
}

请注意,在我的实际代码中,与 create 等效的是一个工厂方法,它可能会返回子类的实例(这就是为什么我选择将其设为静态方法而不是构造函数的原因)。

不幸的是,对于这段代码,我得到以下编译错误:

错误 TS2741:类型“{ prop1: boolean; ”中缺少属性“方法”道具2:字符串; }' 但在“测试”类型中是必需的。

当我在 Visual Studio Code 中将鼠标悬停在 method 上时,Intellisense 正确地将其列为方法,不是属性。但是,错误消息(错误地)指出它是一个属性。

我尝试阅读以下问答,但它们没有帮助我:

error TS2741: Property is missing in type - 接受的答案是关于方法接受的参数类型,但我的 MRE 中的方法不接受参数

How to fix "Property 'type' is missing in type but required in type 'SeriesXrangeOptions'" in angular highcharts module - 解决方案似乎与我的问题无关

Typescript / Angular 2: Property is missing in type - 那是由于不正确地实现接口引起的,但我没有实现接口

谁能解释我为什么会收到这个错误以及如何解决它?

【问题讨论】:

  • 你需要使用new来创建类的实例。

标签: angular typescript angular8


【解决方案1】:

您有一些选择:

  1. 您可以为此使用interface

     static create(prop1 : boolean, prop2 : string) : Test 
     {
       let item : myInterface = {
         prop1: prop1,
         prop2: prop2
       }
    
      return item as Test;
    }
    

Here 是工作示例。

  1. 使用new 关键字和constructor

     static create(prop1 : boolean, prop2 : string) : Test {
         let item = new Test(prop1,prop2);
    
         return item;
       }
    

或者可能像这样部分调用constructor

    public constructor(init?:Partial<Test>) {
        Object.assign(this, init);
    }

Here 是工作示例

【讨论】:

    猜你喜欢
    • 2019-10-30
    • 2022-11-16
    • 2019-06-25
    • 1970-01-01
    • 2017-02-15
    • 2019-11-19
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多