How to parse JSON string in Typescript

后端 未结 7 1509
[愿得一人]
[愿得一人] 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:05

    Type-safe JSON.parse

    You can continue to use JSON.parse, as TS is a JS superset. There is still a problem left: JSON.parse returns any, which undermines type safety. Here are two options for stronger types:

    1. User-defined type guards (playground)

    Custom type guards are the simplest solution and often sufficient for external data validation:

    // For example, you expect to parse a given value with `MyType` shape
    type MyType = { name: string; description: string; }
    
    // Validate this value with a custom type guard
    function isMyType(o: any): o is MyType {
      return "name" in o && "description" in o
    }
    

    A JSON.parse wrapper can then take a type guard as input and return the parsed, typed value:

    const safeJsonParse = (guard: (o: any) => o is T) => (text: string): ParseResult => {
      const parsed = JSON.parse(text)
      return guard(parsed) ? { parsed, hasError: false } : { hasError: true }
    }
    
    type ParseResult =
      | { parsed: T; hasError: false; error?: undefined }
      | { parsed?: undefined; hasError: true; error?: unknown }
    
    Usage example:
    const json = '{ "name": "Foo", "description": "Bar" }';
    const result = safeJsonParse(isMyType)(json) // result: ParseResult
    if (result.hasError) {
      console.log("error :/")  // further error handling here
    } else {
      console.log(result.parsed.description) // result.parsed now has type `MyType`
    }
    

    safeJsonParse might be extended to fail fast or try/catch JSON.parse errors.

    2. External libraries

    Writing type guard functions manually becomes cumbersome, if you need to validate many different values. There are libraries to assist with this task - examples (no comprehensive list):

    • io-ts: rel. popular (3.2k stars currently), fp-ts peer dependency, functional programming style
    • zod: quite new (repo: 2020-03-07), strives to be more procedural/object-oriented than io-ts
    • typescript-is: TS transformer for compiler API, additional wrapper like ttypescript needed
    • typescript-json-schema/ajv: Create JSON schema from types and validate it with ajv

    More infos

    • Runtime type checking #1573
    • Interface type check with Typescript
    • TypeScript: validating external data

提交回复
热议问题