Skip to content

Instantly share code, notes, and snippets.

@palashmon
Created May 13, 2023 16:11
Show Gist options
  • Save palashmon/db68706d4f26d2dbf187e76409905399 to your computer and use it in GitHub Desktop.
Save palashmon/db68706d4f26d2dbf187e76409905399 to your computer and use it in GitHub Desktop.
A super useful type helper in TypeScript by Matt Pocock from Twitter

Use case

Suppose you have a type that has many intersections:

export type SimpleShape = {
  color: string;
} & {
  size: number;
} & {
  shape: "circle" | "square";
};

When you hover over the type SimpleShape with many intersections, it can be difficult to see the resolved type. It would be helpful if there was a way to prettify the display of these types.

With Prettify we can using:

type Shape = Prettify<SimpleShape>;
//   ^? type Shape = {
//        color: string;
//        size: number;
//        shape: "circle" | "square";
//      }

This is really helpful. Thank you, Matt!

/**
* A TypeScript type alias called `Prettify`.
* It takes a type as its argument and returns a new type that has the same properties as the original type,
* but the properties are not intersected. This means that the new type is easier to read and understand.
*/
type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
@rawand-faraidun
Copy link

This works for nested objects

type Prettify<T> = {
  // [K in keyof T]: T[K];
  [K in keyof T]: T[K] extends object ? Prettify<T[K]> : T[K];
  // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
} & unknown;

This works for nested objects

type Prettify<T> = {
  // [K in keyof T]: T[K];
  [K in keyof T]: T[K] extends object ? Prettify<T[K]> : T[K];
  // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
} & unknown;

It does work for objects, but it will also break Classes, for example with this code:

export type Prettify<T> = {
  [K in keyof T]: T[K]
} & {}

you will get this:
image

but with this one:

export type Prettify<T> = {
  [K in keyof T]: T[K] extends object ? Prettify<T[K]> : T[K];
} & {}

you will get this:
image

It would be great if you could check if the T[K]'s type is Real object, if so then prettify it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment