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

I created the following example code to minimally reproduce my problem:

class Test {
  prop1 : boolean
  prop2 : string

  method() { }

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

    return item;
  }
}

Note that the equivalent to create in my actual code is a factory method that might return an instance of a child class (which is why I chose to make this a static method instead of a constructor).

Unfortunately, for this code, I get the following compile error:

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

When I hover over method in Visual Studio Code, Intellisense correctly lists it as a method, not a property. However, the error message (incorrectly) states that it's a property.

I tried reading the following Q&As, but they didn't help me:

error TS2741: Property is missing in type - the accepted answer talks about the type of the parameter that the method accepts, but the method in my MRE doesn't accept a parameter

How to fix "Property 'type' is missing in type but required in type 'SeriesXrangeOptions'" in angular highcharts module - solution appears to be unrelated to my problem

Typescript / Angular 2: Property is missing in type - that one was caused by improperly implementing an interface, but I'm not implementing an interface

Can someone explain why I'm getting this error and how I could fix it?

Upvotes: 1

Views: 4423

Answers (1)

Alireza Ahmadi
Alireza Ahmadi

Reputation: 9953

You have some options to do that:

  1. You can use interface for that:

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

Here is working example.

  1. Use new keyword and constructor:

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

Or maybe partially call constructor like that:

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

Here is working example

Upvotes: 1

Related Questions