Type Query: jQuery Style Type Manipulation

mistlog
ITNEXT
Published in
3 min readOct 30, 2021
convert tuple to object

In this article, we present a new way to create types to use in TypeScript, which allows us to use JavaScript inline to generate complex types easily.

The language we use is TypeType(The Art of Type Programming).

Introduction

In TypeType v0.0.30, we have a new type: ContextType, for example:

sum in typetype

Here we use syntax “``` … ```” to insert JavaScript code, and implement globalContext.sum in this way:

type context

“sum” receives values and return AST in TypeType, and the result is:

sum in ts

This example can be found in https://github.com/mistlog/typetype-template/blob/main/src/type-context.ts.

Type Query

Once we can execute external JavaScript code, we can implement libs to make something likes magic.

As we know, it’s hard to transform union type to tuple type, however, it’s trivial in ContextType:

union to tuple in typetype

Here we use “$.use” to access AST of type variable “input”, and convert it to TupleType in JavaScript:

type query extension

We use “query.install” to add this extension to $: the TypeQuery object, inspired by jQuery.

The output is:

union to tuple in ts

The order is kept as is, actually, you can reorder it as you want.

TypeQuery scales well, you can do something likes this:

and get result:

Examples above can be found in:

Type Testing

We can get AST and types-in-string from Type Runtime, thus we can test types using just plain jest:

Ref: https://github.com/mistlog/typetype-template/blob/main/test/type-runtime.test.ts

Implementation

Code can be found here: https://github.com/mistlog/type-query

For quick start: https://github.com/mistlog/typetype-template

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.

No responses yet

Write a response