The Art of Type Programming

mistlog
ITNEXT
Published in
3 min readMar 11, 2021

Make complex things simple, make simple things trivial.

Types in typescript can get out of control quickly, for example, to merge two objects(599-medium-merge), the solution can be :

or to find diff of two objects(645-medium-diff):

Type Programming vs Type Gymnastics

Yes, we can implement Merge, Diff and then forget about them, as long as it works, we will not concern about that any more. Thus, during the creation of types, tricks are used, spaghetti code such as nested ternary expressions(conditional types) are ignored deliberately.

Great, it just works!

What we don’t do in everyday programming is what we always do in type programming, or more accurately, type gymnastics.

In this article, I’d like to propose that we treat type programming as real programming.

TypeType is used in the following examples, which is a programming language designed for typescript type generation.

Type Statement -> Type Expression

In typetype, we don’t use ternary expression as conditional type, instead, we use traditional if & else.

“type function” is used to declare function of types, type in and type out, which is called “generic” in typescript, but in nature, it’s function of types, we will be explicit about this.

“^{…}” is called block expression, in this block, statement will be translated to type expression in typescript. In this example, “if statement” will be translated to “conditional type” .

You can see it in action in playground: https://mistlog.github.io/typetype-playground/.

To implement “isNumberString”, we have another option now:

Mapped types are represented as “for in statement”:

Then, solutions of Merge and Diff can be:

No tricks

We don’t use tricks to merge objects, instead, we use intuitive object spread syntax. For example, in url-parser-2:

object spread is translated to object$assign:

then we polyfill it to make it available globally:

To conclude

There is nothing special about type programming when we treat it as normal programming. As you can see above, just “if else” or nested “if else” and “for in”.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Published in ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.

Responses (3)

Write a response

Recommended from Medium

Lists

See more recommendations