API reference › @evolu/common › Type › json
function json<T, Name>(
type: T,
name: ValidateChildTypeName<
Name,
BrandType<
Type<
"String",
string,
string,
TypeOfError<"String">,
null,
TypeOfError<"String">,
never,
string,
true
>,
"Json",
JsonError
>
>,
..._validation: [JsonTypeValidationError<T>] extends [never]
? []
: [ValidationFailure<JsonTypeValidationError<T>>]
): readonly [
BrandType<
BrandType<
Type<
"String",
string,
string,
TypeOfError<"String">,
null,
TypeOfError<"String">,
never,
string,
true
>,
"Json",
JsonError
>,
Name,
TypeError<Name> &
TransparentTypeError & {
error: InferErrors<T>;
}
>,
(value: T["Output"]) => string & Brand<"Json"> & Brand<Name>,
(value: string & Brand<"Json"> & Brand<Name>) => T["Output"],
];
Defined in: packages/common/src/Type.ts:14372
Branded Json Type and conversions for another Type.
Use this when a value must be stored as JSON text, such as in a JSON column in an Evolu Schema. It returns a branded Json Type and functions for converting the supplied Type's Output to and from that branded JSON representation.
Example
import {
assertEqual,
assertType,
Age,
NonEmptyTrimmedString100,
json,
object,
type Brand,
} from "@evolu/common";
const User = object({
name: NonEmptyTrimmedString100,
age: Age,
});
const [UserJson, userToUserJson, userJsonToUser] = json(User, "UserJson");
const user = User.orThrow({ name: "Ada", age: 37 });
const userJson = userToUserJson(user);
assertType<string & Brand<"Json"> & Brand<"UserJson">, typeof userJson>();
assertEqual(userJson, '{"name":"Ada","age":37}');
assertEqual(UserJson.orThrow(userJson), userJson);
assertEqual(userJsonToUser(userJson), user);
The supplied Type must have a JSON-compatible CanonicalInput. The branded
Json Type accepts only valid JSON text whose parsed value can be decoded by
the supplied Type.