LoginSignup
1
1

More than 5 years have passed since last update.

【Flow】グローバル変数エラー(Unknown global name)を黙らせる

Last updated at Posted at 2014-11-21

はじめに

参考:Checking third-party code

  • 勉強がてら書いていたら、いつの間にか7割ネタになっていた。
  • Underscore.jsなどサードパーティライブラリに立ちはだかるグローバルの壁
  • 諸々の問題に対してFlowでは Interface Files という機能をサポートしている。

Unknown global name

logic.js
/* @flow */

_.findWhere([{ title: 'A', text: 'B' }, { title: 'C', text: 'D' }], { title: 'C' });


_.each([1, 2, 3], function(v){
  console.log('test:', v);
});

例えば上のようなコードをチェックさせると引っかかる。

error
logic.js: identifier _ Unknown global name

公式の見解

これに対して公式は

fortunately we only need to tell Flow about the parts of the library we're using.

(実際に使う部分だけ interfaces/ とか適当なディレクトリを掘って自分で書いてね)

などと宣っている。(要は以下のように書けと)

interfaces/underscore.js
declare class UnderscoreStatic {
  findWhere<T>(list: Array<T>, properties: {}): T;
  each(list: Array, iteratee: Function): void;
}

declare var _: UnderscoreStatic;

支配欲求の強い貴方へ

  • 手で1行ずつ書いていくのは骨がバキボキに折れる。(何か方法があるのかも?)
  • 「既存コードをとにかく手っ取り早く flow check したい」という 愚かな 願望があるなら any を使う手があるかもしれない。
interfaces/underscore.js
// 「何でもいいからとにかく黙らせる。」
declare var _: any;

ちなみに any 型については

己のコードが絶対にtype correctであるという自信をお持ちならば、anyによってエラーを黙らせることが出来ます。

というような説明が公式にあります。

おわりに

型定義ファイルっぽい奴はいつ来るんですか。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1