TypeScript:与Pick <...>相同,但具有多个字段

时间:2019-12-03 16:48:18

标签: typescript

我使用Pick,但是我如何编写可以选择多个字段的通用PickMulti?

interface MyInterface {
  a: number,
  b: number,
  c: number
}

// this works, but I would like a generic one in number of fields
type AB = Pick<Pick<MyInterface, 'a'>, 'b'>;

// Something like this:
type PickMulti = /* how to write this?*/;
type AB = PickMulti<MyInterface, ['a', 'b']>

1 个答案:

答案 0 :(得分:4)

Pick已经可以用于多个字段,您只需要提供它们作为并集而不是元组/数组类型:

interface MyInterface {
  a: number,
  b: number,
  c: number
}

type AB = Pick<MyInterface, 'a' | 'b'>;

Playground Link