简体   繁体   English

在 TypeScript 中实现“toJson”function 的正确方法是什么?

[英]What is the proper way to implement a 'toJson' function in TypeScript?

I have a custom class, and I need a toJson function. Of course, I can just implement a function called Foo.toJson or Foo.toJsonObject or Foo.jsonify .我有一个自定义的 class,我需要一个toJson function。当然,我可以只实现一个名为Foo.toJsonFoo.toJsonObject或 Foo.jsonify 的Foo.jsonify

But what would be the standard way of doing this?但是这样做的标准方法是什么? I also saw some examples which include a serializer .我还看到了一些包含serializer的示例。 Do I need to go that far?我需要那么远的 go 吗?

Basically I want to be able to make this work:基本上我希望能够完成这项工作:

const foo = new Foo();
fse.writeJson('file.json', foo);

But for a database connection I also need to be able to manually create a json representation:但是对于数据库连接,我还需要能够手动创建一个 json 表示:

const foo = new Foo();
db.writeObject(foo.toJson());

Assuming you can't just modify the original class:假设你不能只修改原来的 class:

  1. Declare a new type which adds the toJSON method to the original type声明一个新类型,将 toJSON 方法添加到原始类型
  2. Cast the object to the new type将object投到新类型
  3. Assign the toJSON method to it为其分配 toJSON 方法

For example:例如:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM