@@ -136,6 +136,16 @@ function array<Item, Options extends ArrayOptions>(
136136 } as unknown as GetType < NonNullable < Item > [ ] , Options > ;
137137}
138138
139+ function constant < Value , Options extends GenericOptions > (
140+ value : Value ,
141+ options ?: Options
142+ ) : GetType < Value , Options > {
143+ return {
144+ ...( options ?. required ? { $required : true } : { } ) ,
145+ enum : [ value ] ,
146+ } as unknown as GetType < Value , Options > ;
147+ }
148+
139149function enumType < Enum , Options extends GenericOptions > (
140150 values : Enum [ ] ,
141151 options ?: Options
@@ -323,6 +333,32 @@ export default {
323333 */
324334 boolean : createSimpleType < boolean > ( 'boolean' ) ,
325335
336+ /**
337+ * Creates a constant value. Useful for creating discriminated unions with the `oneOf` type.
338+ *
339+ * @param value {TValue}
340+ * @param [options] {GenericOptions}
341+ * @param [options.required] {boolean}
342+ *
343+ * @example
344+ * import { schema, types } from 'papr';
345+ *
346+ * schema({
347+ * shape: types.oneOf([
348+ * types.object({
349+ * type: types.constant('circle' as const, { required: true }),
350+ * radius: types.number({ required: true }),
351+ * }),
352+ * types.object({
353+ * type: types.constant('rectangle' as const, { required: true }),
354+ * width: types.number({ required: true }),
355+ * length: types.number({ required: true }),
356+ * }),
357+ * ]),
358+ * });
359+ */
360+ constant,
361+
326362 /**
327363 * Creates a date type.
328364 *
0 commit comments