【问题标题】:How can i disable / handle init, toJSON我如何禁用/处理初始化,toJSON
【发布时间】: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 创建的 inittoJSON,但这会很耗时。

.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,
            };

我想禁用导致错误的inittoJSON,我不需要声明它们可以正常工作。

错误:

键入'{名:字符串;姓氏:字符串; }' 缺少“用户”类型的以下属性:init、toJSON

我想摆脱错误,而不必手动重写整个 NSWAG 生成的 API 客户端。也许我使用错误的类,当使用接口时我得到相同的错误消息。

【问题讨论】:

    标签: typescript .net-core swagger openapi nswag


    【解决方案1】:

    inittoJSON 方法是在您创建 TypeScript 文件并将 DTO 样式设置为 Class 时生成的。如果将该选项设置为接口样式,则不应实现方法,而应仅实现属性。 请参阅以下裁剪图像: DTO settings

    【讨论】:

    • 那行得通。这样做的一个小烦恼是字母“I”不再作为接口名称的前缀。我所有的其他接口都以“I”开头,现在这给代码增加了一些混乱。你知道解决办法吗?
    猜你喜欢
    • 2023-01-16
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多