![](/img/trans.png)
[英]what is the proper way to implement this routine with reduce() function?
[英]What is the proper way to implement a 'toJson' function in TypeScript?
我有一个自定义的 class,我需要一个toJson
function。当然,我可以只实现一个名为Foo.toJson
或Foo.toJsonObject
或 Foo.jsonify 的Foo.jsonify
。
但是这样做的标准方法是什么? 我还看到了一些包含serializer
的示例。 我需要那么远的 go 吗?
基本上我希望能够完成这项工作:
const foo = new Foo();
fse.writeJson('file.json', foo);
但是对于数据库连接,我还需要能够手动创建一个 json 表示:
const foo = new Foo();
db.writeObject(foo.toJson());
假设你不能只修改原来的 class:
例如:
class Foo {
public date: Date;
constructor(date: Date) {
this.date = date;
}
log() {
console.log(this.date.toISOString());
}
}
type ExtendedFoo = Foo & {
toJSON: () => string;
}
const x = new Foo(new Date);
(x as ExtendedFoo).toJSON = function () {
return `"\\/Date(${+this.date})\\/"`
}
x.log();
console.log(x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.