After creating a .NET core 2.2 webapi and utilizing swagger / nswag to generate the API for my React / typescript application, I encountered a ts(2739) message when attempting to set up a new object:
Type '{ firstName: string; lastName: string; }' is missing the following properties from type 'User': init, toJSON
Is there a way to globally disable or handle this issue? It functions correctly, but I would prefer to eliminate the error (perhaps with a ts-ignore?).
I've tested various solutions like the following;
Error but data is read:
const newUser: User = {
firstName,
lastName,
};
No error but data is not read:
const newUser = new User ({
firstName,
lastName,
});
An alternative would be to remove all nswag created init and toJSON methods, but that would be too time-consuming.
.NETCore Model (Baseclass is simply the Id and createdAtDate)
public class User : BaseModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Image { get; set; }
}
}
Generated Typescript Nswag Code
export interface IBaseModel {
id?: string | null;
creationDate?: Date | null;
updateDate?: Date | null;
}
export class User extends BaseModel implements IUser {
firstName?: string | null;
lastName?: string | null;
image?: string | null;
constructor(data?: IUser) {
super(data);
}
init(data?: any) {
super.init(data);
if (data) {
this.firstName = data["firstName"] !== undefined ? data["firstName"] : <any>null;
this.lastName = data["lastName"] !== undefined ? data["lastName"] : <any>null;
this.image = data["image"] !== undefined ? data["image"] : <any>null;
}
}
static fromJS(data: any): User {
data = typeof data === 'object' ? data : {};
let result = new User();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["firstName"] = this.firstName !== undefined ? this.firstName : <any>null;
data["lastName"] = this.lastName !== undefined ? this.lastName : <any>null;
data["image"] = this.image !== undefined ? this.image : <any>null;
super.toJSON(data);
return data;
}
}
export interface IUser extends IBaseModel {
firstName?: string | null;
lastName?: string | null;
image?: string | null;
}
Typescript use class as type
const newUser: User = {
firstName,
lastName,
};
I seek to disable the init and toJSON methods that are causing the error, without having to declare them to function.
Error:
Type '{ firstName: string; lastName: string; }' is missing the following properties from type 'User': init, toJSON
I want to resolve the errors without manually rewriting the entire NSWAG generated API client. Perhaps I am mishandling the classes; when using the interfaces, I receive the same error message.