【发布时间】:2020-02-01 02:00:08
【问题描述】:
我创建了一个 .NET core 2.2 webapi,并使用 swagger / nswag 为我的 React / typescript 应用程序生成 API。当我尝试设置一个新对象时,我收到一条ts(2739) 消息:
键入'{名:字符串;姓氏:字符串; }' 缺少“用户”类型的以下属性:init、toJSON
有没有办法在全局范围内禁用/处理这个?它可以正常工作,但我想摆脱错误(也许是 ts-ignore?)
我已经尝试过多种这样的解决方案;
错误但读取数据:
const newUser: User = {
firstName,
lastName,
};
没有错误但不读取数据:
const newUser = new User ({
firstName,
lastName,
});
我还可以删除所有 nswag 创建的 init 和 toJSON,但这会很耗时。
.NETCore 模型(Baseclass 只是 Id 和 createdAtDate)
public class User : BaseModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Image { get; set; }
}
}
生成的 Typescript Nswag 代码
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 使用类作为类型
const newUser: User = {
firstName,
lastName,
};
我想禁用导致错误的init 和toJSON,我不需要声明它们可以正常工作。
错误:
键入'{名:字符串;姓氏:字符串; }' 缺少“用户”类型的以下属性:init、toJSON
我想摆脱错误,而不必手动重写整个 NSWAG 生成的 API 客户端。也许我使用错误的类,当使用接口时我得到相同的错误消息。
【问题讨论】:
标签: typescript .net-core swagger openapi nswag