When using lodash, you can utilize the _.invert
function to switch an object's keys and values:
var object = { 'a': 'x', 'b': 'y', 'c': 'z' };
_.invert(object);
// => { 'x': 'a', 'y': 'b', 'z': 'c' }
The current definitions in the lodash typings always specify a string
→string
mapping for this function:
_.invert(object); // type is _.Dictionary<string>
However, in certain cases, particularly when utilizing a const assertion, a more accurate type might be necessary:
const o = {
a: 'x',
b: 'y',
} as const; // type is { readonly a: "x"; readonly b: "y"; }
_.invert(o); // type is _.Dictionary<string>
// but it would ideally be { readonly x: "a", readonly y: "b" }
Is there a way to achieve typings that precise? The following declaration comes close:
declare function invert<
K extends string | number | symbol,
V extends string | number | symbol,
>(obj: Record<K, V>): {[k in V]: K};
invert(o); // type is { x: "a" | "b"; y: "a" | "b"; }
While the keys are correct, the values result in a union of input keys, meaning the specificity of the mapping is lost. Is it possible to achieve perfect precision in this scenario?