Utilities for checking the types of values at runtime, helpful for working with external or async loaded data within TypeScript.
Create a suite of typeguard functions for the given object shape.
-
shape
- The shape of the object to create a typeguard for.
Returns: DecoratedTypeguard
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
});
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
Check a single non-object type.
-
value
- The value to check the type of -
checker
- The type expression to check against
Returns: boolean
Check the type validity of the elements in an array.
-
value
- The value to check the type of -
checker
- The type expression to check against
Returns: boolean
Quickly check a single object shape.
-
value
- The value to test the type validity of -
shape
- The shape the object should be, as a typeguard shape
Returns: boolean