@sinclair/typebox
Version:
Json Schema Type Builder with Static Type Resolution for TypeScript
46 lines (44 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Partial = void 0;
const index_1 = require("../optional/index");
const index_2 = require("../object/index");
const index_3 = require("../intersect/index");
const index_4 = require("../union/index");
const index_5 = require("../discard/index");
const index_6 = require("../symbols/index");
const type_1 = require("../clone/type");
const partial_from_mapped_result_1 = require("./partial-from-mapped-result");
// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
const type_2 = require("../guard/type");
// prettier-ignore
function FromRest(T) {
return T.map(L => PartialResolve(L));
}
// prettier-ignore
function FromProperties(T) {
return globalThis.Object.getOwnPropertyNames(T).reduce((Acc, K) => {
return { ...Acc, [K]: (0, index_1.Optional)(T[K]) };
}, {});
}
// ------------------------------------------------------------------
// PartialResolve
// ------------------------------------------------------------------
// prettier-ignore
function PartialResolve(T) {
return ((0, type_2.IsIntersect)(T) ? (0, index_3.Intersect)(FromRest(T.allOf)) :
(0, type_2.IsUnion)(T) ? (0, index_4.Union)(FromRest(T.anyOf)) :
(0, type_2.IsObject)(T) ? (0, index_2.Object)(FromProperties(T.properties)) :
(0, index_2.Object)({}));
}
/** `[Json]` Constructs a type where all properties are optional */
function Partial(T, options = {}) {
if ((0, type_2.IsMappedResult)(T))
return (0, partial_from_mapped_result_1.PartialFromMappedResult)(T, options);
const D = (0, index_5.Discard)(T, [index_6.TransformKind, '$id', 'required']);
const R = (0, type_1.CloneType)(PartialResolve(T), options);
return { ...D, ...R };
}
exports.Partial = Partial;