跳到主要内容

静态类型:Flow To TypeScript类型 — Numio

使用 Khan Academy 的 flow-to-ts 将带 Flow 类型的代码转换为 TypeScript。Maybe 类型(?T)变为 T | null | undefined,精确对象变为普通对象类型,$ReadOnlyArray 变为 ReadonlyArray。

你正逐个文件把 Flow 代码库迁移到 TypeScript,想为每个模块先做一遍初步转换。

Flow

TypeScript

适用场景

  • 你正逐个文件把 Flow 代码库迁移到 TypeScript,想为每个模块先做一遍初步转换。
  • 需要把旧 React 项目中带 Flow 类型的代码片段粘贴到 TypeScript 代码库中。

使用方法

  1. 将 Flow 代码粘贴到 Flow 面板。
  2. 代码会提交到 /api/flow-to-typescript,在服务器上用 flow-to-ts 转换;没有任何设置。
  3. 复制 TypeScript,保存为 .ts 或 .tsx,然后运行 tsc 修正转换无法处理的部分。

Flow

// @flow
import type { Node } from 'react';

export type User = {|
  +id: number,
  name: ?string,
  roles: $ReadOnlyArray<string>,
|};

export function greet(user: User): string {
  return `Hi ${user.name ?? 'guest'}`;
}

export const render = (title: string): Node => null;

TypeScript

import type { Node } from "react"
export type User = {
  readonly id: number
  name: string | null | undefined
  roles: ReadonlyArray<string>
}
export function greet(user: User): string {
  return `Hi ${user.name ?? "guest"}`
}
export const render = (title: string): Node => null

功能与限制

页面会把输入发送到服务器路由(/api/flow-to-typescript)进行转换,并不只在浏览器中处理。Next.js API 路由默认接受最大 1 MB 的请求体。

精确对象类型 {| |} 会失去精确性,因为 TypeScript 没有精确对象;+prop 变为 readonly。

$ReadOnly、$Keys 等 Flow 工具类型会保留原名,并从 npm 包 utility-types 导入,因此需要另行安装该包。

// @flow 指令会被移除,代码会重新输出。Node 等 React 类型导入会按原样保留,需要自行重命名(例如 ReactNode)。

FAQ

Maybe 类型如何转换?

name: ?string 会变为 name: string | null | undefined。可选属性(name?: T)仍然是可选的。

能转换 JSX 文件吗?

能。JSX 会被保留,因此请将结果保存为 .tsx。

能只得到 .d.ts 而不是完整代码吗?

本页面不行。Flow to TypeScript Declaration 使用同一服务器路由并设置 declarationOnly,只生成声明。

规范与参考资料