iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌟

I created a VSCode extension to expand and visualize TypeScript types

に公開
2021/05/31
4件

I've created a VSCode extension that expands hard-to-read TypeScript types to make them easier to understand!

Motivation

When writing TS, I often encounter situations where I can't read the types, so I have to bind them to variables or explore them via autocomplete. I kept wondering if there was something that would let me view expanded types.

I learned about something called the CompilerAPI for TypeScript, so I thought, "Why not just extract the types nicely and pass them to a VSCode tree view?" I searched for it and found that others had attempted the same thing, but unfortunately, they had given up.

The story of how type-explorer failed - sisisin's blog

In short, the compilerAPI doesn't have a rich enough API to allow for sequential expansion.

However, I also wanted to try developing an extension, so I gave it a try anyway. It turned out pretty well, so I decided to release it.

What I built

It is an extension that can expand TypeScript type definitions.

You can install it from ts-type-expand - Visual Studio Marketplace.

As shown above, you can expand hard-to-read types in VSCode as much as you need to check them.

When you hover over a variable, the type information appears, but it often says something like User & Foo & Bar, and you might not know what the final type actually is. You can use this in those kinds of situations.

As for supported types, since type resolution is handled by the CompilerAPI, all types supported by TS should be expandable.

The repository is d-kimuson/ts-type-expand: vscode extension for expand type of typescript.

How To

I used the CompilerAPI to extract the type information for the node selected in VSCode and pass it to the tree view.

For the CompilerAPI, I referred to materials like:

I learned the basics by referencing these materials, and then extracted the types through trial and error.

It was quite difficult because sometimes the necessary types were not provided when receiving Union types (the entity existed, but the type definition didn't, so I had to find and use properties through trial and error), and there weren't many materials available to understand how to get the desired types. However, I kept at it until I was able to extract them properly.

Tree View API

I expanded the extracted types using the VSCode TreeView.

The API for this was quite simple, so I managed to build it without much trouble.

However, in situations where you want to expand types:

  • Viewing properties
  • Viewing Union candidates
  • Viewing Enum candidates
  • Expanding functions (arguments and return values)

There are many patterns, but visually, it's just expanding something that is folded. When I tried using it, the user experience was a bit subtle—it felt like "I know I can expand it, but I don't know what I can expand or what is currently expanded."

After tinkering with it a bit, I found that if you set a description for TreeItem:

You can display additional information, so I made it possible to grasp what kind of meaning can be expanded.

Problems I faced

Cannot use recursive types

At first, I used the CompilerAPI to fully expand the types and pass them to the tree view, but as you might expect, recursive types caused an infinite loop.

type User = {
  friend: User
}

In terms of performance, it's better to expand them sequentially to avoid unnecessary calculations, so I modified it to only acquire necessary properties at the timing of the tree view expansion.

It stopped working after I published it, even though it worked locally

It worked fine locally, but after publishing and installing it, the built-in types stopped working.

type Foo = Array<string>
type Bar = Pick<Hoge, "key1", "key2">

Things like these were all broken.

The conclusion is that I had accidentally excluded necessary files in .vscodeignore.

I used the TypeScript boilerplate created by $ yo code almost as is, but the initial setting of .vscodeignore was to not send *.ts files.

It seems it was kind enough to specify that since common extensions only need to send JS, but in this case, the CompilerAPI refers to built-in type definitions under node_modules when interpreting types, so I needed to remove them from the ignore list.

.gitignore
 .vscode/**
 .vscode-test/**
 out/test/**
 src/**
 .gitignore
 .yarnrc
 vsc-extension-quickstart.md
 **/tsconfig.json
 **/.eslintrc.json
 **/*.map
-*.ts
+src/**/*.ts

Future plans

It turned out to be quite useful, so I plan to keep using it myself and expand its functionality.

Currently, it cannot expand array types (expanding User when it is User[]), so I want to make that expandable. Also, the number of places for cursor selection is limited, so I want to increase that.

The most common use case is "extracting and expanding type information from the used variable." Currently, it can only be expanded from variable declarations, so I want to support that while adding more locations such as function arguments.

  • With version upgrades, you can now get types from almost anywhere, such as variables, function calls, and arguments if you select where it seems possible to get them.

  • Added support for array type expansion as well.

It's a bit rough, but please feel free to use it!

ts-type-expand - Visual Studio Marketplace

References

Discussion

masakinihirotamasakinihirota

WindowsのVSCodeで試してみました。
しかし型情報は表示されませんでした。

やったことの再現

拡張機能のインストール
ts-type-expand - Visual Studio Marketplace
https://marketplace.visualstudio.com/items?itemName=kimuson.ts-type-expand

ターミナルから
npm init -y
npm install --save-dev typescript
tsc --init

Newfileを適当に作成
sample.ts

import type * as ts from "typescript";

function hello(name: string): void {
  console.log("Hello " + name + "!");
}
let your_name: string = "Yamada";
hello(your_name);

export type MyType = ts.Type & {
  types?: MyType[];
};

export type BaseType = {
  name?: string;
  typeText: string;
  props: PropType[];
  union: BaseType[];
  typeForProps: MyType | undefined;
};

export type PropType = BaseType & {
  propName: string;
};

VSCodeのエディタ部分の型の上にマウスカーソルをホバーすると型情報は表示されますが、
TS TYPE EXPANDの部分には何も表示されませんでした。

1
きむそんきむそん

インストールと報告ありがとうございます!

tsconfig.json は開いているワークスペースの直下に置かれていますか? サブディレクトリ等にある場合は、ts-type-expand.tsconfigPath にパスを渡すか、tsconfig.json が直下に置かれるように開き直してみてください

あるいは、windows 環境での問題かもしれません
手元に windows マシンがないので試せなくて申し訳ないんですが、C:\Users\<User>\.vscode\extensions\kimuson.ts-type-expand-0.0.7 に移動して、

$ rm -rf node_modules && npm install

をして、VSCode をリロードしてみてください

それでもダメなら、VSCode のメニュー → ヘルプ → 開発者ツールの切り替えで、ts-type-expand の起動に失敗するログが流れると思うので、そちらを教えていただければお力になれるかもしれません

masakinihirotamasakinihirota

無事表示することが出来ました。
自分の勘違いでした。
ワークスペースは開いたフォルダのことだと思い込んでいたからでした。

VSCodeでフォルダを開いた後に名前をつけてワークスペースを保存とすると。
そのフォルダがワークスペースとなり、
そうなるとTS TYPE EXPANDが有効になり型情報が表示されるようになりました。
お騒がせして申し訳ありませんでした。

1
きむそんきむそん

ワークスペースを保存しなくても動くはずなんですが、謎ですね
とりあえず動いたようで良かったです!