UNPKG

variant

Version:

Variant types (a.k.a. Discriminated Unions) in TypeScript

27 lines 1.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.partialLookup = exports.lookup = void 0; /** * Process an unknown variant by comparing it to a provided lookup table and returning the proper result. * @param obj some object that extends `{[K]: string}`. * @param handler a lookup table going from the various keys of `obj`'s type to any. * @param typeKey the key used as the discriminant. */ function lookup(obj, handler, typeKey) { const typeString = obj[typeKey !== null && typeKey !== void 0 ? typeKey : 'type']; return handler[typeString]; } exports.lookup = lookup; /** * Process an unknown variant by comparing it to a provided lookup table and returning the proper result. * If the handler does not account for the case, returns undefined * @param obj some object that extends `{[K]: string}`. * @param handler a partial lookup table going from some keys of `obj`'s type to any. * @param typeKey the key used as the discriminant. */ function partialLookup(obj, handler, typeKey) { // Takes advantage of the fact that handler with missing keys will return undefined. return lookup(obj, handler, typeKey); } exports.partialLookup = partialLookup; //# sourceMappingURL=lookup.js.map