본문으로 건너뛰기

Flow에서 TypeScript 선언 파일 생성 — Numio

flow-to-ts로 Flow 코드를 TypeScript로 변환한 뒤, TypeScript 컴파일러로 .d.ts 선언 파일만 생성합니다. 본문은 제거되고 기본값이 있는 매개변수는 선택적 매개변수가 됩니다.

패키지가 Flow로 작성되어 있고, 소스를 옮기지 않고 TypeScript 사용자에게 TypeScript 타입을 제공하고 싶을 때.

Flow

TypeScript Declarations

이럴 때 사용하세요

  • 패키지가 Flow로 작성되어 있고, 소스를 옮기지 않고 TypeScript 사용자에게 TypeScript 타입을 제공하고 싶을 때.
  • Flow 모듈이 export하는 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 타입은 예시의 Label처럼 T | null | undefined가 됩니다.

파일 하나만 컴파일되며, import한 타입은 해석되지 않습니다.

FAQ

async 함수와 Promise 반환 타입이 유지되나요?

네. export async function load(id: number): Promise<Tag>는 export declare function load(id: number): Promise<Tag>가 됩니다.

매개변수 기본값은 어떻게 되나요?

제거되고 매개변수는 선택적이 됩니다. b: Point = ORIGIN은 b?: Point가 됩니다.

타입 별칭이 유지되나요?

네. export된 타입 별칭은 변환된 TypeScript 형태로 나타납니다. 페이지가 Prettier로 포맷하므로 들여쓰기는 공백 두 칸이고 세미콜론은 없습니다.

사양 및 참고 자료