space-lift
Version:
TypeScript Array, Object, Map, Set, Union, Enum utils
20 lines (19 loc) • 705 B
JavaScript
/**
* Creates a type-safe union, providing: derived types, factories and type-guards in a single declaration.
*/
export 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 });
}