Compute / Resolve / Beautify

Utility

Handy Utility for you to use:

/**
* Force TS to resolve composed types
* Use case: for display purposes, we want to show all properties of a type
*/
type Compute<T> = {
[K in keyof T]: T[K]
}

Example

/**
* Force TS to resolve composed types
* Use case: for display purposes, we want to show all properties of a type
*/
type Compute<T> = {
[K in keyof T]: T[K]
}

type Point2D = {
x: number,
y: number,
}

// Compare hover info
type Point3D = Point2D & { z: number }

// Compare hover info
type ComputedPoint3D = Compute<Point3D>;
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

TypeScript types can be hard to view when they are composed of other types. Let's take a look at an example. We have a type defining a 0.2 D consisting of two members, X and Y of type number, and we want to create a new type called point type 3D that extends 0.2 D with another member called Z. As you can see, it is quite easy to achieve within an intersection type. However, when we hover over 0.3 D, we don't really get to see all the members that exist within 0.3 D. We only get to see the member Z, and then we sort of have to do the math ourselves to see what members are there in 0.2 D.

00:35

While the combined type is perfectly fine in terms of type checking, it would be great if you could look at the final computer result. When we hover over a type just for such developer ergonomics, you can build a custom compute type function quite easily. So let's build this compute type, which will take a type as an input using a generic, and then expand that using a MA type, making sure that the output has all of the same items as the input type T. Now, this compute type function is actually something that we've already looked at in our maps type lesson, and it is fundamentally an identity type that is the output

01:09

of the function is exactly the same as the input of the function, and while it doesn't serve any purpose in terms of type checking modifications, it does serve a purpose in terms of resolving a composed type and listing out all of its members in the output. Let's see, yes, utility. By applying it to the 0.3 D type, currently, 0.3 D does not list out all of its members. However, in the output you can see a new type has been computed. That does list out all of the members that were finally resolved.