跳到主要内容

类型声明:Flow To TypeScript声明 — Numio

先用 flow-to-ts 将 Flow 代码转换为 TypeScript,再由 TypeScript 编译器只生成 .d.ts 声明文件。函数体会被移除,带默认值的参数变为可选参数。

某个包用 Flow 编写,你想在不迁移源码的情况下为 TypeScript 用户提供 TypeScript 类型。

Flow

TypeScript Declarations

适用场景

  • 某个包用 Flow 编写,你想在不迁移源码的情况下为 TypeScript 用户提供 TypeScript 类型。
  • 你想对比 Flow 模块导出的 API 与对应的 TypeScript 版本。

使用方法

  1. 将 Flow 模块粘贴到 Flow 面板。
  2. 代码会带着 declarationOnly 参数提交到 /api/flow-to-typescript;服务器将其转换为 TypeScript 并生成声明。
  3. 从 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 类型变为 T | null | undefined,如示例中的 Label。

只编译一个文件;导入的类型不会被解析。

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 格式化结果,因此使用两个空格缩进且不带分号。

规范与参考资料