LoginSignup
11
6

More than 3 years have passed since last update.

【TypeScript】toJSONメソッドでJSON.stringifyの挙動をカスタマイズする

Posted at

privateを含む3つのプロパティを持つクラスModelを考える。

class Model {
  constructor(
    public prop1: string,
    private prop2: string,
    public prop3: number,
  ) { }
}

ModelクラスのインスタンスをJSON.stringifyでJSON文字列化すると、実行時はJavaScriptになっておりprivateであることは忘れられているのでprivateなプロパティまで文字列になってしまう。

const model = new Model("value1", "value2", 3);

console.log(JSON.stringify(model));
// {"prop1":"value1","prop2":"value2","prop3":3}

privateプロパティを表示しないようにするためにはModelクラスにtoJSONメソッドを定義する。
toJSONメソッドの戻り値は、Modelクラスの代わりにJSON文字列化したい値にしておく。(文字列化した結果ではなく)

class Model {
  constructor(
    public prop1: string,
    private prop2: string,
    public prop3: number,
  ) { }

  toJSON = () => {
    return {
      prop1: this.prop1,
      prop3: this.prop3,
    }
  }

  // こうではない
  // toJSON = () => {
  //   return JSON.stringify({
  //     prop1: this.prop1,
  //     prop3: this.prop3,
  //   });
  // }
}

JSON.stringifytoJSONを持つオブジェクトを文字列化するときはtoJSONで返却される値を利用してくれる。

const model = new Model("value1", "value2", 3);

console.log(JSON.stringify(model));
// {"prop1":"value1","prop3":3}

参考

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6