typescript 如何在打字稿 2.0 / 3.0 中添加自定义“打字”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38971984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add custom "typings" in typescript 2.0 / 3.0
提问by Lu4
回答by MisterMetaphor
You can create local custom typings just for your project, where you can declare types for JS libraries. For that, you need to:
您可以仅为您的项目创建本地自定义类型,您可以在其中声明 JS 库的类型。为此,您需要:
Create directory structure to keep your type declaration files so that your directory structure looks similar to this:
. ├── custom_typings │?? └── some-js-lib │?? └── index.d.ts └── tsconfig.json
In the
index.d.ts
file, add a declaration for your JS library:declare module 'some-js-lib' { export function hello(world: string): void }
Add a reference to this type declaration in the
compilerOptions
section of yourtsconfig.json
:{ "compilerOptions": { ... "typeRoots": ["./node_modules/@types", "./custom_typings"] }, ... }
Use the declared module in your code:
import { hello } from 'some-js-lib' hello('world!')
创建目录结构以保留您的类型声明文件,以便您的目录结构类似于以下内容:
. ├── custom_typings │?? └── some-js-lib │?? └── index.d.ts └── tsconfig.json
在
index.d.ts
文件中,为您的 JS 库添加一个声明:declare module 'some-js-lib' { export function hello(world: string): void }
在
compilerOptions
您的部分中添加对此类型声明的引用tsconfig.json
:{ "compilerOptions": { ... "typeRoots": ["./node_modules/@types", "./custom_typings"] }, ... }
在代码中使用声明的模块:
import { hello } from 'some-js-lib' hello('world!')