计算值可索引的对象中键名的并集类型

时间:2019-09-20 14:33:41

标签: typescript

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

此问题是https://github.com/microsoft/TypeScript/issues/33521的继续。到目前为止,我在此TS Playground link中尝试建立此功能。

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

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

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

1 个答案:

答案 0 :(得分:2)

您正在寻找这样的东西:

type KeysMatching<T, V> = NonNullable<
  { [K in keyof T]: T[K] extends V ? K : never }[keyof T]
>;

其中KeysMatching<T, V>为您提供T的键,其属性可分配给V。通过looks upmapped类型的属性值来执行此操作。展示其工作方式的示例:

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

这是这样评估的:

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

哪个给了"a"


然后,IndexableKeys就是:

type IndexableKeys<T> = KeysMatching<T, keyof any>;

和您的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);
};

您的测试将达到预期的效果:

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: () => {}
  }
]);

希望有所帮助;祝你好运!

conditional