我目前正在开发一个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
我真的很好奇这是否在 TypeScript 中存在某种设计差距。\n假设我有一个函数,它接受任何满足此接口的对象
\ninterface Params {\n [key: string]: string | number | boolean | undefined | null;\n}\nRun Code Online (Sandbox Code Playgroud)\n因此键必须是字符串,属性的类型可以是原始类型或 void。
\n如果我现在指定一些采用特定接口的方法,该接口本身满足 Params 接口,我会收到错误,另一个接口没有索引签名。\n因此另一个接口可能看起来像这样。
\ninterface Foo {\n bar: string;\n}\nRun Code Online (Sandbox Code Playgroud)\n我还尝试将签名更改为Record<string, string | number | boolean | undefined | null>,但这也给出了缺少索引签名错误。
我的整个代码可能看起来像这样。给出一个完整的图片。所以我需要指定对象的键和值类型,以便能够在中执行某些操作Object.entries
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}\nRun Code Online (Sandbox Code Playgroud)\n编辑: \n重要说明,特定函数的行为应该保持不变,因为它应该用于缩小允许的接口,因为在这种特殊情况下,只允许具有某些属性的对象来确保特定的结果。
\n我不知何故发现将事件侦听器添加到文档的行为有点奇怪。虽然向 HTMLElements 添加侦听器工作正常,但向文档添加侦听器不起作用。但奇怪的是,使用 jQuery 使它工作。
那么有人可以解释一下,为什么这两个函数没有做完全相同的事情?
["customEvent1", "customEvent2"].forEach(
(event: string) => {
document.addEventListener(event, () => this.eventHandler());
});
$(document).on("customEvent1 customEvent2", () => this.eventHandler());
Run Code Online (Sandbox Code Playgroud)
编辑:嗯,似乎对环境存在一些误解。
$(document).trigger("customEvent1");