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 types?
type C = Something<T1, T2> // { y: number }
TypeScript allows you to define multiple types. The terminology for this is union types and it allows you to define a variable as a string, or a number, or an array, or an object, etc. We can create union types by using the pipe symbol ( | ) between each type.
TypeScript has two special types, null and undefined , that have the values null and undefined respectively. We mentioned these briefly in the Basic Types section. By default, the type checker considers null and undefined assignable to anything. Effectively, null and undefined are valid values of every type.
An intersection type is a type that merges several kinds into one. This allows you to combine many types to create a single type with all of the properties that you require. An object of this type will have members from all of the types given. The '&' operator is used to create the intersection type.
TypeScript Union Type Narrowing To narrow a variable to a specific type, implement a type guard. Use the typeof operator with the variable name and compare it with the type you expect for the variable.
Use static keyof
operator:
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 A
and B
.
Each value associated to this key will have type A[K] | B[K]
, in case A[K]
and B[K]
are different.
Use Conditional Type to map key to value only if type 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 }
From this object, get union of all values, by accessing all keys:
// `never` will not appear in the union type Kc = MappedC[keyof A & keyof B]
Finally:
type C = { [K in Kc]: A[K] }
Based on @kube's answer, you could use generics to create a reusable type:
type Common<A, B> = { [P in keyof A & keyof B]: A[P] | B[P]; }
This allows you to create intersections on the fly:
const c: Common<T1, T2> = { y: 123 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With