Reputation: 12191
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
Reputation: 9953
You have some options to do that:
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.
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