How to parse JSON string in Typescript

后端 未结 7 1483
[愿得一人]
[愿得一人] 2020-12-04 18:29

Is there a way to parse strings as JSON in Typescript.
Example: In JS, we can use JSON.parse(). Is there a similar function in Typescript?

I have a

7条回答
  •  温柔的废话
    2020-12-04 19:14

    If you want your JSON to have a validated Typescript type, you will need to do that validation work yourself. This is nothing new. In plain Javascript, you would need to do the same.

    Validation

    I like to express my validation logic as a set of "transforms". I define a Descriptor as a map of transforms:

    type Descriptor = {
      [P in keyof T]: (v: any) => T[P];
    };
    

    Then I can make a function that will apply these transforms to arbitrary input:

    function pick(v: any, d: Descriptor): T {
      const ret: any = {};
      for (let key in d) {
        try {
          const val = d[key](v[key]);
          if (typeof val !== "undefined") {
            ret[key] = val;
          }
        } catch (err) {
          const msg = err instanceof Error ? err.message : String(err);
          throw new Error(`could not pick ${key}: ${msg}`);
        }
      }
      return ret;
    }
    

    Now, not only am I validating my JSON input, but I am building up a Typescript type as I go. The above generic types ensure that the result infers the types from your "transforms".

    In case the transform throws an error (which is how you would implement validation), I like to wrap it with another error showing which key caused the error.

    Usage

    In your example, I would use this as follows:

    const value = pick(JSON.parse('{"name": "Bob", "error": false}'), {
      name: String,
      error: Boolean,
    });
    

    Now value will be typed, since String and Boolean are both "transformers" in the sense they take input and return a typed output.

    Furthermore, the value will actually be that type. In other words, if name were actually 123, it will be transformed to "123" so that you have a valid string. This is because we used String at runtime, a built-in function that accepts arbitrary input and returns a string.

    You can see this working here. Try the following things to convince yourself:

    • Hover over the const value definition to see that the pop-over shows the correct type.
    • Try changing "Bob" to 123 and re-run the sample. In your console, you will see that the name has been properly converted to the string "123".

提交回复
热议问题