object-shape-tester
Version:
Test object properties and value types.
37 lines (36 loc) • 1.11 kB
JavaScript
import { Kind, Type, TypeRegistry } from '@sinclair/typebox';
import { defineShape } from '../shape/shape.js';
export { Kind } from '@sinclair/typebox';
/**
* Easily create a custom shape.
*
* @category Shape
* @example
*
* ```ts
* import {checkValidShape, createCustomShape} from 'object-shape-tester';
* import {UtcIsoString, isValidIsoString} from 'date-vir';
*
* const utcIsoStringShape = createCustomShape({
* default: new Date().toISOString() as UtcIsoString,
* name: 'UtcIsoString',
* checkValue(value) {
* return isValidIsoString(value);
* },
* });
*
* const myShape = utcIsoStringShape();
*
* checkValidShape(new Date().toISOString(), myShape); // `true`
* checkValidShape('', myShape); // `false`
* ```
*/
export function createCustomShape({ checkValue, default: outerDefaultValue, name, }) {
if (!TypeRegistry.Has(name)) {
TypeRegistry.Set(name, (schemaOptions, value) => checkValue(value));
}
return (defaultValue = outerDefaultValue) => defineShape(Type.Unsafe({
[Kind]: name,
default: defaultValue,
}));
}