object-shape-tester
Version:
Test object properties and value types.
38 lines (37 loc) • 1.26 kB
JavaScript
import { combineErrorMessages, extractErrorMessage, log } from '@augment-vir/common';
import { Kind, Type, TypeRegistry } from '@sinclair/typebox';
import { defineShape } from '../shape/shape.js';
/**
* Creates a shape for a specific class. Value checks are done through `instanceof`.
*
* @category Shape
* @example
*
* ```ts
* import {classShape, checkValidShape} from 'object-shape-tester';
*
* const myShape = classShape(RegExp);
*
* checkValidShape(/hi/, myShape); // `true`
* checkValidShape('hi', myShape); // `false`
* ```
*/
export function classShape(classConstructor, defaultValue) {
if (!TypeRegistry.Has(classShape.name)) {
TypeRegistry.Set(classShape.name, (schema, value) => value instanceof schema.classConstructor);
}
return defineShape(Type.Unsafe({
[Kind]: classShape.name,
classConstructor,
default: defaultValue ?? createClassDefaultValue(classConstructor),
}));
}
function createClassDefaultValue(classConstructor) {
try {
return new classConstructor();
}
catch (caught) {
log.error(combineErrorMessages(`Failed to create classShape default value for class '${classConstructor.name}':`, extractErrorMessage(caught)));
return {};
}
}