LoginSignup
20
18

More than 5 years have passed since last update.

Typescriptで手っ取り早く外部ライブラリを使う

Last updated at Posted at 2015-08-11

Typescriptをコンパイルする際に、コンパイラの知らない変数や関数を使おうとすると怒られます。

  • hello.ts
(() => jQuery("div").css("background", "red"))();
$ tsc hello.ts
> hello.ts(1,8): error TS2304: Cannot find name 'jQuery'.

それでもちゃんとコンパイルはしてくれるので通常はそこまで問題でもありませんが、
環境によってはタスクランナーを止めてくれたりする事もあります。
(riot.jsでTypescriptを利用する場合など)
こういう場合は型定義ファイル等を持ってくるのですが面倒なので、一行追加してあげます。

  • hello.ts
declare var jQuery: any;
(() => jQuery("div").css("background", "red"))();
$ tsc hello.ts
> 問題なく変換

次に、window直下等に変数を追加するタイプの場合

  • world.ts
(() => window.superagent.get("http://google.com/") )();
$ tsc world.ts
> world.ts(1,15): error TS2339: Property 'superagent' does not exist on type 'Window'.

こういう場合はinterfaceを利用します

  • world.ts
interface Window {
  superagent: any;
}
(() => window.superagent.get("http://google.com/") )();
$ tsc world.ts
> 問題なく変換

手っ取り早く黙らせる事ができました。

20
18
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
20
18