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

前端 未结 3 1379
迷失自我
迷失自我 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:24

    Based on @kube's answer, you could use generics to create a reusable type:

    type Common = {
        [P in keyof A & keyof B]: A[P] | B[P];
    }
    

    This allows you to create intersections on the fly:

    const c: Common = { y: 123 };
    

提交回复
热议问题