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

There are 2 types

type A = {
  x: number
  y: number
}

type B = {
  y: number
  z: number
}

How to get a type with common properties of these types?

type C = Something<T1, T2> // { y: number }
+5
source share
2 answers

General properties

Use the static operator keyof:

type Ka = keyof A // 'x' | 'y'
type Kb = keyof B // 'y' | 'z'
type Kc = Ka & Kb // 'y'

And define a Mapped Type with properties in Kc:

type C = {
  [K in keyof A & keyof B]: A[K] | B[K]
}

This defines a new type where each key will be present both in Aand inB

Each value associated with that key will be of type A[K] | B[K] A[K] | B[K]if A[K]and B[K]different.


Common properties with the same types only

Use a conditional type to map the key to a value only if the type is the same in A and B:

type MappedC = {
  [K in keyof A & keyof B]:
    A[K] extends B[K] // Basic check for simplicity here.
    ? K // Value becomes same as key
    : never // Or 'never' if check did not pass
}

, :

// 'never' will not appear in the union
type Kc = MappedC[keyof A & keyof B]

:

type C = {
  [K in Kc]: A[K]
}
+6

@kube answer generics :

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

" ":

const c: Common<T1, T2> = { y: 123 };
0

Source: https://habr.com/ru/post/1689520/


All Articles