space-lift
Version:
TypeScript Array, Object, Map, Set, Union, Enum utils
24 lines (23 loc) • 840 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUnion = void 0;
/**
* Creates a type-safe union, providing: derived types, factories and type-guards in a single declaration.
*/
function createUnion(description) {
const factories = Object.keys(description).reduce((acc, key) => {
const factory = description[key];
const factoryWithType = (...args) => (Object.assign({ type: key }, factory.apply(null, args)));
acc[key] = factoryWithType;
return acc;
}, {});
const isCache = {};
function is(type) {
if (isCache[type])
return isCache[type];
isCache[type] = (obj) => obj.type === type;
return isCache[type];
}
return Object.assign(Object.assign({}, factories), { is });
}
exports.createUnion = createUnion;