[英]How to add custom “typings” in typescript 2.0 / 3.0
You can create local custom typings just for your project, where you can declare types for JS libraries.您可以仅为您的项目创建本地自定义类型,您可以在其中声明 JS 库的类型。 For that, you need to:为此,您需要:
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:在index.d.ts
文件中,为您的 JS 库添加一个声明:
declare module 'some-js-lib' { export function hello(world: string): void }
(Optional: skip if you have TypeScript >= 4.x) Add a reference to this type declaration in the compilerOptions
section of your tsconfig.json
: (可选:如果您有 TypeScript >= 4.x,请跳过)在tsconfig.json
的compilerOptions
部分中添加对此类型声明的引用:
{ "compilerOptions": { ... "typeRoots": ["./node_modules/@types", "./custom_typings"] }, ... }
Use the declared module in your code:在代码中使用声明的模块:
import { hello } from 'some-js-lib' hello('world!')
Assuming you have your external js package installed under node_modules, I think there are two options: 假设您在node_modules下安装了外部js包,我认为有两种选择:
provide a typescript declaration file in the package , and add a reference to it: 在包中提供一个打字稿声明文件 ,并添加对它的引用:
// node_modules/secret-package/index.d.ts export interface SecretInterface { // ¯\\_(ツ)_/¯ }
And reference the typings file in the package.json: 并引用package.json中的typings文件:
// node_modules/secret-package/package.json { ..., "typings": "./index.d.ts", ..., }
augment the module in a declaration file of your project 在项目的声明文件中扩充模块
// index.d.ts declare module 'secret-package' { interface SecretInterface { // ¯\\_(ツ)_/¯ } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.