parse() functions

export namespace json {
  export function isParse<T>(input: string): Primitive<T> | null;
  export function assertParse<T>(input: string): Primitive<T>;
  export function validateParse<T>(input: string): IValidation<Primitive<T>>;
}

Type safe JSON parser.

Unlike native JSON.parse() function which returns any typed instance without type checking, typia.json.assertParse<T>() function validates instance type after the parsing. If the parsed value is not following the promised type T, it throws TypeGuardError with the first type error info.

If you want to know every type error infos detaily, you can use typia.json.validateParse<T>() function instead. Otherwise, you just only want to know whether the parsed value is following the type T or not, just call typia.json.isParse<T>() function.

Look at the below code, then you may understand how the typia.json.assertParse<T>() function works.

examples/src/assertParse.ts
import typia, { tags } from "typia";
 
const json: string = JSON.stringify(typia.random<IMember>());
const parsed: IMember = typia.json.assertParse<IMember>(json);
 
console.log(json === JSON.stringify(parsed)); // true
 
interface IMember {
  id: string & tags.Format<"uuid">;
  email: string & tags.Format<"email">;
  age: number &
    tags.Type<"uint32"> &
    tags.ExclusiveMinimum<19> &
    tags.Maximum<100>;
}

Reusable functions

export namespace json {
  export function createIsParse<T>(): (input: string) => Primitive<T> | null;
  export function createAssertParse<T>(): (input: string) => Primitive<T>;
  export function createValidateParse<T>(): (
    input: string,
  ) => IValidation<Primitive<T>>;
}

Reusable typia.json.isParse<T>() function generators.

If you repeat to call typia.json.isParse<T>() function on the same type, size of JavaScript files would be larger because of duplicated AOT compilation. To prevent it, you can generate reusable function through typia.createIsParse<T>() function.

Just look at the code below, then you may understand how to use it.

examples/src/createIsParse.ts
import typia, { tags } from "typia";
 
export const parseMember = typia.json.createIsParse<IMember>();
 
interface IMember {
  id: string & tags.Format<"uuid">;
  email: string & tags.Format<"email">;
  age: number &
    tags.Type<"uint32"> &
    tags.ExclusiveMinimum<19> &
    tags.Maximum<100>;
}