object-shape-tester
Version:
Test object properties and value types.
36 lines (35 loc) • 1.1 kB
JavaScript
import { getEnumValues } from '@augment-vir/common';
import { Type } from '@sinclair/typebox';
import { defineShape } from '../shape/shape.js';
/**
* Creates a shape that requires matching a value within the given enum.
*
* @category Shape
* @example
*
* ```ts
* import {enumShape, checkValidShape} from 'object-shape-tester';
*
* enum MyEnum {
* A = 'a',
* B = 'b',
* }
*
* const myShape = enumShape(MyEnum);
*
* checkValidShape(MyEnum.A, myShape); // `true`
* checkValidShape('a', myShape); // `true`
* checkValidShape('c', myShape); // `false`
* ```
*/
export function enumShape(enumObject,
/** If omitted or `undefined`, the first value in the enum object will be used as the default. */
defaultValue) {
const enumValues = getEnumValues(enumObject);
if (defaultValue != undefined && !enumValues.includes(defaultValue)) {
throw new TypeError(`enumShape default must be a subset of the given enum.`);
}
return defineShape(Type.Union(enumValues.map((value) => Type.Literal(value)), {
default: defaultValue ?? enumValues[0],
}));
}