UNPKG

object-shape-tester

Version:
48 lines (47 loc) 1.41 kB
import { isShapeDefinitionKey } from './shape-keys.js'; import { isShapeDefinition } from './shape-specifiers.js'; import { shapeToDefaultValue } from './shape-to-default-value.js'; export { shapeToDefaultValue } from './shape-to-default-value.js'; /** * Creates a {@link ShapeDefinition} from any input. This produces both a type and a default value. * This is the core of the `object-shape-tester` package; {@link ShapeDefinition} instances are used * for all of the shape checking. * * @category Main * @example * * ```ts * import {defineShape} from 'object-shape-tester'; * * const myShape = defineShape({ * a: '', * b: -1, * }); * * function doThing( * // using the generated type and default value * input: typeof myShape.runtimeType = myShape.defaultValue, * ) {} * ``` */ export function defineShape(shape, isReadonly = false) { if (isShapeDefinition(shape)) { return shape; } const shapeDefinition = { shape, isReadonly, get defaultValue() { return shapeToDefaultValue(shape); }, [isShapeDefinitionKey]: true, }; Object.defineProperty(shapeDefinition, 'runtimeType', { enumerable: false, configurable: false, get() { throw new Error(`runtimeType cannot be used as a value, it is only for types.`); }, }); return shapeDefinition; }