🍃このブログは移転しました。
3秒後、自動的に移動します・・・。

Flowでコンストラクタをエクスポートするモジュールの型を定義する

こういうやつ。

import EventEmitter from 'events';

const ee = new EventEmitter(); // <- コレ

これはあくまで例で、Node標準の`events`のEventEmitterなら、Flowがビルトインで型情報を持ってるので困りません。
でも似たようなのを自分で書いたり、他のライブラリに型をつける場合に必要になるはず。

こう書く

declare module 'events' {
  declare class EventEmitter {
  }

  declare var exports: typeof EventEmitter;
}

Is there a way to tell Flow an exported module _is_ a class? · Issue #769 · facebook/flow · GitHub

ちなみに、こういう書き方で迷ったら、flow-typedを適当に眺めると見つかったりもする。

GitHub - flowtype/flow-typed: A central repository for Flow library definitions

相変わらず公開されてるモジュールは少ない・・・( ˘ω˘)

ふつうにエクスポートしたい場合

declare module 'my-module' {
  declare module.exports: {
    foo(): void;
    bar(baz: number): boolean;
  }
}

// or

declare module 'my-module' {
  declare function foo(): void;
  declare function bar(baz: number): boolean;
}

ってすれば動く。

Creating Library Definitions | Flow

ちなみにDefault + Namedエクスポートしたい場合

declare module 'socket.io-client' {
  declare class IOSocket {
    connected: boolean;
    on(eventName: string, callback: (*) => *): void;
    emit(eventName: string, ...args: *[]): void;
    connect(): void;
    disconnect(): void;
  }

  declare export default (url: string, options?: Object) => IOSocket;
  declare export var IOSocket: typeof IOSocket;
}

みたいにすれば、

import io from 'socket.io-client';
import type { IOSocket } from 'socket.io-client';

const socket: IOSocket = io(url);

ってできる。


このへんまじで正解がわからん・・。