是否可以在TypeScript中精确键入_.invert?

时间:2019-06-02 14:10:48

标签: typescript lodash typescript-generics typescript-declarations

在lodash中,_.invert函数会反转对象的键和值:

var object = { 'a': 'x', 'b': 'y', 'c': 'z' };

_.invert(object);
// => { 'x': 'a', 'y': 'b', 'z': 'c' }

lodash的键入currently声明为始终返回stringstring映射:

_.invert(object);  // type is _.Dictionary<string>

但是有时候,尤其是如果您使用的是const assertion,更精确的类型是合适的:

const o = {
  a: 'x',
  b: 'y',
} as const;  // type is { readonly a: "x"; readonly b: "y"; }
_.invert(o);  // type is _.Dictionary<string>
              // but would ideally be { readonly x: "a", readonly y: "b" }

是否可以精确地输入?该声明接近:

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"; }

键是正确的,但是值是输入键的并集,即您失去了映射的特异性。有可能做到这一点吗?

3 个答案:

答案 0 :(得分:2)

您可以使用保留正确值的更复杂的映射类型来做到这一点:

const o = {
    a: 'x',
    b: 'y',
} as const;

type AllValues<T extends Record<PropertyKey, PropertyKey>> = {
    [P in keyof T]: { key: P, value: T[P] }
}[keyof T]
type InvertResult<T extends Record<PropertyKey, PropertyKey>> = {
    [P in AllValues<T>['value']]: Extract<AllValues<T>, { value: P }>['key']
}
declare function invert<
    T extends Record<PropertyKey, PropertyKey>
>(obj: T): InvertResult<T>;

let s = invert(o);  // type is { x: "a"; y: "b"; }

AllValues首先创建一个包含所有keyvalue对的并集(因此在您的示例中为{ key: "a"; value: "x"; } | { key: "b"; value: "y"; })。然后,在映射类型中,我们映射联合中的所有value类型,对于每个value,我们使用key提取原始Extract。只要没有重复的值(如果有重复的值,我们将在出现值的地方获得键的并集)将很好地工作

答案 1 :(得分:2)

Titian Cernicova-Dragomir的解决方案非常酷。今天,我找到了另一种替换条件类型的对象键和值的方法:

type KeyFromValue<V, T extends Record<PropertyKey, PropertyKey>> = {
  [K in keyof T]: V extends T[K] ? K : never
}[keyof T];

type Invert<T extends Record<PropertyKey, PropertyKey>> = {
  [V in T[keyof T]]: KeyFromValue<V, T>
};

使用const o测试:

const o = {
  a: "x",
  b: "y"
} as const;

// type Invert_o = {x: "a"; y: "b";}
type Invert_o = Invert<typeof o>;

// works
const t: Invert<typeof o> = { x: "a", y: "b" };
// Error: Type '"a1"' is not assignable to type '"a"'.
const t1: Invert<typeof o> = { x: "a1", y: "b" };

以与上述答案相同的方式声明invert函数,返回类型为Invert<T>

Playground

答案 2 :(得分:0)

有了TypeScript 4.1对Key Remapping in Mapped Types的支持,这变得相当简单:

const o = {
    a: 'x',
    b: 'y',
} as const;

declare function invert<
    T extends Record<PropertyKey, PropertyKey>
>(obj: T): {
    [K in keyof T as T[K]]: K
};

let s = invert(o);  // type is { readonly x: "a"; readonly y: "b"; }

playground