Typescript how to create type with common properties of two types?

前端 未结 3 1377
迷失自我
迷失自我 2020-12-29 07:04

There are 2 types

type A = {
  x: number
  y: number
}

type B = {
  y: number
  z: number
}

How to get type with common properties of that

3条回答
  •  臣服心动
    2020-12-29 07:30

    Extract common props with same types only

    Based on @kube's answer,

    type Common = Pick<
      A,
      {
        [K in keyof A & keyof B]: A[K] extends B[K]
          ? B[K] extends A[K]
            ? K
            : never
          : never;
      }[keyof A & keyof B]
    >;
    

提交回复
热议问题