计算值可索引的对象中键名的联合类型

Jas*_*hrt 2 typescript

我想编写一个indexByProp函数,将要索引的道具的选择限制为可索引值(字符串、数字、符号)。

此问题是https://github.com/microsoft/TypeScript/issues/33521的延续。到目前为止,我尝试构建此函数可以在此TS Playground 链接中找到。

我期望的预期结果是,例如:

indexByProp('bar', [{ // should be ok
  bar: 1, 
  foo: '2', 
  qux: () => {}
}])

indexByProp('qux', [{ // should be type error
  bar: 1, 
  foo: '2', 
  qux: () => {}
}])
Run Code Online (Sandbox Code Playgroud)

jca*_*alz 5

你正在寻找这样的东西:

type KeysMatching<T, V> = NonNullable<
  { [K in keyof T]: T[K] extends V ? K : never }[keyof T]
>;
Run Code Online (Sandbox Code Playgroud)

where 为您提供可分配给 的属性KeysMatching<T, V>的键。它查找映射的条件类型的属性值来执行此操作。展示其工作原理的示例:TV

interface Foo {
  a?: string;
  b: number;
}

// give me all the keys of Foo whose properties are assignable to 
// string | undefined... expect to get "a" back
type Example = KeysMatching<Foo, string | undefined>;
Run Code Online (Sandbox Code Playgroud)

这是这样评估的:

type Example2 = NonNullable<
  {
    a?: Foo["a"] extends string | undefined ? "a" : never;
    b: Foo["b"] extends string | undefined ? "b" : never;
  }["a" | "b"]
>;

type Example3 = NonNullable<
  {
    a?: string | undefined extends string | undefined ? "a" : never;
    b: number extends string ? "b" : never;
  }["a" | "b"]
>;

type Example4 = NonNullable<{ a?: "a"; b: never }["a" | "b"]>;

type Example5 = NonNullable<"a" | undefined | never>;

type Example6 = NonNullable<"a" | undefined>;

type Example7 = "a";
Run Code Online (Sandbox Code Playgroud)

"a"正如预期的那样。


那么,IndexableKeys就只是:

type IndexableKeys<T> = KeysMatching<T, keyof any>;
Run Code Online (Sandbox Code Playgroud)

你的indexByProp()函数看起来像:

const indexByProp = <X extends Indexable>(
  propName: IndexableKeys<X>,
  xs: X[]
): Indexable<X> => {
  const seed: Indexable<X> = {};
  return xs.reduce((index, x) => {
    const address = x[propName];
    index[address as keyof typeof index] = x; // need assertion
    return index;
  }, seed);
};
Run Code Online (Sandbox Code Playgroud)

并且您的测试按预期运行:

indexByProp("bar", [
  {
    bar: 1,
    foo: "2",
    qux: () => {}
  }
]); // okay

indexByProp("qux", [
  //        ~~~~~  error!
  // Argument of type '"qux"' is not assignable to parameter of type '"bar" | "foo"'.
  {
    // should be type error
    bar: 1,
    foo: "2",
    qux: () => {}
  }
]);
Run Code Online (Sandbox Code Playgroud)

希望有帮助;祝你好运!

链接到代码