object-shape-tester
Version:
Test object properties and value types.
43 lines (42 loc) • 1.01 kB
JavaScript
import { filterMap, getObjectTypedEntries, } from '@augment-vir/common';
import { Type } from '@sinclair/typebox';
import { defineShape } from '../shape/shape.js';
/**
* Creates a shape by picking specific keys off of another object shape.
*
* @category Shape
* @example
*
* ```ts
* import {pickShape, checkValidShape} from 'object-shape-tester';
*
* const myShape = pickShape(
* {
* hi: '',
* bye: -1,
* },
* {
* hi: true,
* },
* );
*
* checkValidShape(
* {
* hi: 'some value',
* },
* myShape,
* ); // `true`
* checkValidShape(
* {
* hi: 'some value',
* bye: 100,
* },
* myShape,
* ); // `false`
* ```
*/
export function pickShape(originalShape, selection) {
const schema = defineShape(originalShape).$_schema;
const pickKeys = filterMap(getObjectTypedEntries(selection), ([key]) => key, (key, [, enabled,]) => !!enabled);
return defineShape(Type.Pick(schema, pickKeys));
}