Package Exports
- types-json
Readme
Type checking for JSON values.
If I should maintain this repo, please ⭐️
DM me on Twitter if you have questions or suggestions.
This package uses zod to type check JSON values.
It includes type guards for each of the JSON types, as well as parse functions and corresponding types.
Contents
Installation
yarn add types-jsonnpm install types-jsonpnpm add types-jsonUsage
JSONValue
When using isJSONValue, values which cannot be parsed or serialized properly using JSON.parse and JSON.stringify return false.
Similarly, when using parseJSONValue, invalid values return undefined.
Finally, a zod schema provided representing the JSONValue type.
import { isJSONValue, parseJSONValue, jsonValueSchema } from "types-json";
isJSONValue(undefined); // false
isJSONValue(null); // true
isJSONValue(NaN); // false
isJSONValue(Infinity); // false
isJSONValue([1, 2, 3]); // true
isJSONValue([1, 2, () => 3]); // falseTypes
Here are the full types:
import { JSONObject, JSONValue, JSONArray } from "types-json";
type JSONObject = {
[key in string]?: JSONValue
};
type JSONValue = string | number | boolean | null | JSONObject | JSONArray;
interface JSONArray extends Array<JSONValue> {};JSONObject
import {
isJSONObject,
parseJSONObject,
jsonObjectSchema
} from "types-json";
isJSONObject({ foo: "bar" }); // true
isJSONObject({ foo: () => "bar" }); // false
parseJSONObject({ foo: "bar" }); // true
parseJSONObject({ foo: () => "bar" }); // undefinedJSONArray
import {
isJSONArray,
parseJSONArray,
jsonArraySchema,
} from "types-json";
isJSONArray([1]); // true
isJSONArray([1, () => 2]); // false
parseJSONArray([1]); // []
parseJSONArray([1, () => 2]); // undefinedString
import {
isString,
parseString,
stringSchema
} from "types-json";
isString("foo"); // true
isString(1); // undefined
parseString("foo"); // "foo"
parseString(1); // undefinedNumber
import {
isNumber,
parseNumber,
numberSchema
} from "types-json";
isNumber(1); // true
isNumber("1"); // undefined
parseNumber(1); // true
parseNumber("1"); // undefinedBoolean
import {
isBoolean,
parseBoolean,
booleanSchema
} from "types-json";
isBoolean(true); // true
isBoolean("true"); // undefined
parseBoolean(true); // true
parseBoolean("true"); // undefinedNull
import {
isNull,
parseNull,
nullSchema
};
isNull(null); // true
isNull("not null"); // undefined
parseNull(null); // null
parseNull("not null"); // undefinedUndefined
Finally, an isUndefined type guard is provided:
import { isUndefined } from "types-json";
isUndefined(undefined); // true
isUndefined("string"); // falseDependencies
- zod: TypeScript-first schema declaration and validation library with static type inference
Dev Dependencies
- autorepo: Autorepo abstracts away your dev dependencies, providing a single command to run all of your scripts.
License 
MIT - MIT License
Related Packages
- types-pkg-json: Type checking for package.json
- types-tsconfig: Type checking for tsconfig.json
- types-eslintrc: Type checking for .eslintrc.json