由于方法的存在导致错误 TS2741 ("property... is missing in type")

Error TS2741 ("property... is missing in type") being caused by the existence of a method

我创建了以下示例代码以尽可能少地重现我的问题:

class Test {
  prop1 : boolean
  prop2 : string

  method() { }

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

    return item;
  }
}

请注意,在我的实际代码中等同于 create 的工厂方法可能 return 一个子实例 class(这就是为什么我选择将其设为静态方法而不是构造函数)。

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

error TS2741: Property 'method' is missing in type '{ prop1: boolean; prop2: string; }' but required in type 'Test'.

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

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

- 接受的答案讨论了方法接受的参数类型,但我的 MRE 中的方法不接受参数

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

- 那个是接口实现不当造成的,我没有实现接口

有人可以解释为什么我会收到此错误以及我该如何解决它吗?

您有一些选择:

  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 是工作示例