object-shape-tester
Version:
Test object properties and value types.
38 lines (37 loc) • 1.01 kB
JavaScript
import { Type } from '@sinclair/typebox';
import { defineShape } from '../shape/shape.js';
/**
* Creates a shape that merges multiple objects together. Note that intersecting fixed properties
* with a `recordShape` (or other generic mapped object keys) is not supported and will break in
* many ways.
*
* @category Shape
* @example
*
* ```ts
* import {intersectShape, checkValidShape} from 'object-shape-tester';
*
* const myShape = intersectShape(
* {
* a: '',
* },
* {
* b: '',
* },
* );
*
* checkValidShape({a: 'hi', b: 'bye'}, myShape); // `true`
* checkValidShape({a: 'hi'}, myShape); // `false`
* ```
*/
export function intersectShape(...inits) {
const combinedDefault = {};
const schemas = inits.map((init) => {
const shape = defineShape(init);
Object.assign(combinedDefault, shape.default);
return shape.$_schema;
});
return defineShape(Type.Composite(schemas, {
default: combinedDefault,
}));
}