flatten the type of a recursive object in typescript

To flatten the type of a recursive object in TypeScript, we can use the type aliases feature in TypeScript. We first define an interface with a set of properties that are either primitive types or arrays of the same interface type. Then, we create a type alias that recursively hovers over the child property types to flatten the object type.

index.ts
interface SomeInterface {
  prop1: string;
  prop2: number;
  children?: SomeInterface[];
}

type FlattenedInterface = SomeInterface & { children: FlattenedInterface }[];

172 chars
9 lines

In this example, we add a children property to SomeInterface which is an optional array of the same interface type SomeInterface. We can then create a FlattenedInterface type alias that flattens the interface by defining its type as an array of SomeInterface, where each element contains a flattened children property.

This technique works well for flattening the types of arbitrarily deep object hierarchies.

gistlibby LogSnag