如何编写PickByValue类型?

时间:2019-03-13 20:33:09

标签: typescript

Pick类型包含在TypeScript中。它的实现如下:

type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};

您将如何编写PickByValue类型,以使以下各项起作用:

type Test = {
  includeMe: 'a' as 'a',
  andMe: 'a' as 'a',
  butNotMe: 'b' as 'b',
  orMe: 'b' as 'b'
};

type IncludedKeys = keyof PickByValue<Test, 'a'>;
// IncludedKeys = 'includeMe' | 'andMe'

1 个答案:

答案 0 :(得分:0)

假设您打算Test成为这样:

type Test = {
  includeMe: 'a',
  andMe: 'a',
  butNotMe: 'b',
  orMe: 'b'
};

,并假设您希望PickByValue<T, V>给出V子类型的所有属性(因此PickByValue<T, unknown>应该是T) ,则可以这样定义PickByValue

type PickByValue<T, V> = Pick<T, { [K in keyof T]: T[K] extends V ? K : never }[keyof T]>
type TestA = PickByValue<Test, 'a'>; // {includeMe: "a"; andMe: "a"}
type IncludedKeys = keyof PickByValue<Test, 'a'>; // "includeMe" | "andMe"

但是,如果您只需要IncludedKeys,则可以使用KeysMatching<T, V>更直接地做到这一点:

type KeysMatching<T, V> = {[K in keyof T]: T[K] extends V ? K : never}[keyof T];
type IncludedKeysDirect = KeysMatching<Test, 'a'> // "includeMe" | "andMe"

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