FlowからTypeScript宣言への生成 — Numio
flow-to-ts で Flow のコードを TypeScript に変換し、その後 TypeScript コンパイラーで .d.ts 宣言ファイルだけを出力します。本体は削除され、デフォルト値のある引数は省略可能になります。
パッケージが Flow で書かれており、ソースを移行せずに TypeScript の利用者向けに型定義を配布したい場合。
Flow
TypeScript Declarations
こんなときに使えます
- パッケージが Flow で書かれており、ソースを移行せずに TypeScript の利用者向けに型定義を配布したい場合。
- Flow モジュールのエクスポートされた API を、TypeScript での同等の形と比較したい場合。
使い方
- Flow パネルに Flow のモジュールを貼り付けます。
- コードは declarationOnly を指定して /api/flow-to-typescript に送信され、サーバーが TypeScript に変換して宣言を出力します。
- TypeScript Declarations パネルから結果をコピーし、パッケージのエントリーポイントの隣にある index.d.ts に貼り付けます。
Flow
// @flow
export type Point = { x: number, y: number };
export type Shape = 'circle' | 'square';
export type Label = ?string;
export const ORIGIN: Point = { x: 0, y: 0 };
export function distance(a: Point, b: Point = ORIGIN): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}
export class Canvas {
shapes: Shape[] = [];
draw(shape: Shape, at?: Point): void { this.shapes.push(shape); }
}TypeScript 宣言 (.d.ts)
export type Point = {
x: number
y: number
}
export type Shape = "circle" | "square"
export type Label = string | null | undefined
export declare const ORIGIN: Point
export declare function distance(a: Point, b?: Point): number
export declare class Canvas {
shapes: Shape[]
draw(shape: Shape, at?: Point): void
}仕様と制限
入力は変換のためにサーバーのルート(/api/flow-to-typescript)に送信されます。ブラウザ内だけで処理されるわけではありません。Next.js の API ルートが受け付けるリクエストボディは、デフォルトで 1 MB までです。
TypeScript の ES2020 と DOM のライブラリファイルが読み込まれるため、Array<T>、Promise、Date、$ReadOnlyArray(ReadonlyArray に変換)は書かれたとおりに宣言に現れます。
Maybe 型は、例の Label のように T | null | undefined になります。
コンパイルされるのは 1 ファイルだけで、インポートした型は解決されません。
FAQ
async 関数と Promise の戻り値の型は残りますか?
はい。export async function load(id: number): Promise<Tag> は export declare function load(id: number): Promise<Tag> になります。
引数のデフォルト値はどうなりますか?
削除され、引数は省略可能になります。b: Point = ORIGIN は b?: Point になります。
型エイリアスは残りますか?
はい。エクスポートされた型エイリアスは TypeScript に変換された形で出力されます。ページが Prettier で整形するため、インデントは 2 スペースでセミコロンは付きません。