類型定義文件(*.d.ts)
要在TypeScript引用第三方JavaScript庫和框架,首先要了解TypeScript的類型定義文件。TypeScript的類型定義文件用來幫助開發者在TypeScript中使用已有的
JavaScript的工具包,如:Jquery。所有的類型定義文件都是以.d.ts結尾的。這個文件實際上就是一個TypeScript模塊,它把你要使用的JavaScript工具包裏邊的工具
以TypeScript的類或者模塊的方式暴露(export)出來,供你在你的模塊裏去import。
如何獲得類型定義文件
以Jquery爲例:
1. 在github上有公開的項目DefinitelyTyped,裏面有大多數會用到的類型定義文件,找到Jquery的類型定義文件index.d.ts下載下來拷貝進項目中,項目就可以用
jquery來寫代碼了,而且有代碼提示。github地址:https://github.com/DefinitelyTyped/DefinitelyTyped
2.還可以用typings工具,這個工具是用來專門安裝類型定義文件的。
首先用npm來安裝typings工具,安裝後,就可以用typings命令查詢一個項目、關鍵字或框架了,用typings命令把需要的第三方庫或框架安裝上就可以在項目中直接
使用了。
# Install Typings CLI utility. npm install typings --global # Search for definitions. typings search tape # Find a definition by name. typings search --name react # If you use the package as a module: # Install non-global typings (defaults to "npm" source, configurable through `defaultSource` in `.typingsrc`). typings install debug --save # If you use the package through `<script>`, it is part of the environment, or # the module typings are not yet available, try searching and installing with `--global`: typings install dt~mocha --global --save # If you need a specific commit from github. typings install d3=github:DefinitelyTyped/DefinitelyTyped/d3/d3.d.ts#1c05872e7811235f43780b8b596bfd26fe8e7760 --global --save # Search and install by version. typings info env~node --versions typings install [email protected] --global --save # Install typings from a particular source (use `<source>~<name>` or `--source <source>`). typings install env~atom --global --save typings install bluebird --source npm --save # Use `typings/index.d.ts` (in `tsconfig.json` or as a `///` reference). cat typings/index.d.ts