小编DaS*_*Sch的帖子

TypeScript/Angular2中的DTO设计

我目前正在开发一个Angular 2应用程序.在开发过程中,我开始使用TypeScript类从JSON创建对象,我通过HTTP或在表单中创建新对象时创建对象.

例如,该类可能看起来像这样.

export class Product {
    public id: number;
    public name: string;
    public description: string;
    public price: number;
    private _imageId: number;
    private _imageUrl: string;

    constructor(obj: Object = {}) {
        Object.assign(this, obj);
    }

    get imageId(): number {
        return this._imageId;
    }
    set imageId(id: number) {
        this._imageId = id;
        this._imageUrl = `//www.example.org/images/${id}`;
    }

    get imageUrl(): string {
        return this._imageUrl;
    }

    public getDTO() {
        return {
            name: this.name,
            description: this.description,
            imageId: this.imageId,
            price: this.price
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,上面显示的这个解决方 但现在让我们假设对象中有更多属性,我想要一个干净的DTO(例如没有私有属性),通过POST将此Object发送到我的服务器.一个更通用的getDTO()功能怎么样?我想避免列出很长的财产分配清单.我在考虑为属性使用装饰器.但我真的不知道如何使用它们来过滤DTO的属性.

software-design restful-architecture typescript ecmascript-6

7
推荐指数
1
解决办法
7023
查看次数

定义没有索引签名的打字稿对象形状

我真的很好奇这是否在 TypeScript 中存在某种设计差距。\n假设我有一个函数,它接受任何满足此接口的对象

\n
interface Params {\n    [key: string]: string | number | boolean | undefined | null;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

因此键必须是字符串,属性的类型可以是原始类型或 void。

\n

如果我现在指定一些采用特定接口的方法,该接口本身满足 Params 接口,我会收到错误,另一个接口没有索引签名。\n因此另一个接口可能看起来像这样。

\n
interface Foo {\n    bar: string;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

我还尝试将签名更改为Record<string, string | number | boolean | undefined | null>,但这也给出了缺少索引签名错误。

\n

我的整个代码可能看起来像这样。给出一个完整的图片。所以我需要指定对象的键和值类型,以便能够在中执行某些操作Object.entries

\n
function specificFunction(obj: Foo) {\n  genericFunction(obj);\n}\n\nfunction genericFunction(params: Params) {\n  Object.entries(params).forEach(([key, value]) => {\n    \xe2\x80\xa6\n  })\n}\n
Run Code Online (Sandbox Code Playgroud)\n

编辑: \n重要说明,特定函数的行为应该保持不变,因为它应该用于缩小允许的接口,因为在这种特殊情况下,只允许具有某些属性的对象来确保特定的结果。

\n

typescript

5
推荐指数
1
解决办法
770
查看次数

document.addEventListener 与 $(document).on

我不知何故发现将事件侦听器添加到文档的行为有点奇怪。虽然向 HTMLElements 添加侦听器工作正常,但向文档添加侦听器不起作用。但奇怪的是,使用 jQuery 使它工作。

那么有人可以解释一下,为什么这两个函数没有做完全相同的事情?

["customEvent1", "customEvent2"].forEach(
    (event: string) => {
        document.addEventListener(event, () => this.eventHandler());
    });

$(document).on("customEvent1 customEvent2", () => this.eventHandler());
Run Code Online (Sandbox Code Playgroud)

编辑:嗯,似乎对环境存在一些误解。

  1. 函数被一个类包围
  2. 我正在使用 TypeScript/ES6
  3. EventHandler 是一个类方法
  4. 自定义事件由触发$(document).trigger("customEvent1")

javascript jquery typescript ecmascript-6

4
推荐指数
1
解决办法
1847
查看次数