@devs-toolbox/typeguard
v1.0.1
Published
Simple typeguard definitions
Downloads
4
Readme
Dev's Toolbox // Typeguard
Utilities for checking the types of values at runtime, helpful for working with external or async loaded data within TypeScript.
API
createObjectTypeguard(shape)
Create a suite of typeguard functions for the given object shape.
shape
- The shape of the object to create a typeguard for.
Returns: DecoratedTypeguard
Shape
A TypeGuard Shape is an object whose keys specify how to analyze an objects types.
const guards = createObjectTypeguard({
id: "number", // Strings imply "typeof" checks
name: "string",
active: "boolean",
notes: {array: "string"}, // An array of strings
metadata: {record: ["string", "number", "boolean"]} // A record whose values are strings, numbers or booleans
website: {optional: "string"} // Optional value
version: {literal: 1} // Literal value
});
DecoratedTypeguard
The return value of createObjectTypeguard
is a function which can take an object and check if it matches the provided shape. This function also contains three additional guards as properties:
const isThing = createObjectTypeguard(THING_SHAPE);
isThing(value); // Check if `value` satisfies Thing
isThing.strict(value); // Check if `value` is exactly a Thing with no additional properties
isThing.array(value); // Check if `value` is an array of Things
isThing.strictArray(value); // Check if `value` is an array of strictly-checked Things
checkValue(value, checker)
Check a single non-object type.
value
- The value to check the type ofchecker
- The type expression to check against
Returns: boolean
checkArray(value checker)
Check the type validity of the elements in an array.
value
- The value to check the type ofchecker
- The type expression to check against
Returns: boolean
checkObject(value, shape)
Quickly check a single object shape.
value
- The value to test the type validity ofshape
- The shape the object should be, as a typeguard shape
Returns: boolean