UNPKG

object-shape-tester

Version:
34 lines (33 loc) 970 B
import { Type, } from '@sinclair/typebox'; import { TypeSystemPolicy } from '@sinclair/typebox/system'; import { defineShape } from '../shape/shape.js'; /** * Creates a shape that allows an object property to be missing. * * @category Shape * @example * * ```ts * import {optionalShape, checkValidShape, defineShape} from 'object-shape-tester'; * * const myShape = defineShape({ * a: '', * b: optionalShape(-1), * }); * * checkValidShape({a: 'hi', b: 0}, myShape); // `true` * checkValidShape({a: 'hi'}, myShape); // `true` * checkValidShape({b: 0}, myShape); // `false` * ``` */ export function optionalShape(shape, options = {}) { TypeSystemPolicy.ExactOptionalPropertyTypes = true; const shapeSchema = defineShape(shape).$_schema; const schema = options.alsoUndefined ? Type.Union([ Type.Undefined(), shapeSchema, ]) : shapeSchema; return defineShape(Type.Optional(schema)); }