Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 } 
like image 286
Kirill A Avatar asked Nov 19 '17 10:11

Kirill A


People also ask

How do I assign two TypeScript types?

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.

Can be two types TypeScript?

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.

How do you define intersection types in TypeScript?

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.

How do you handle a union type in TypeScript?

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.


2 Answers

Common Properties

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.


Common Properties with Same Types only

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] } 
like image 180
kube Avatar answered Sep 17 '22 22:09

kube


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 }; 
like image 39
Fabian Lauer Avatar answered Sep 18 '22 22:09

Fabian Lauer