且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有 Typescript 打字的情况下使用节点模块

更新时间:2021-11-23 22:32:56

应该在哪个文件夹中定义该文件?

In which folder should that file be defined?

这些文件实际上可以在任何文件夹中声明,但是***将它们放在一个描述它们是什么的目录中.在我们的项目中,我们有一个名为ambient-types"的文件夹,其中有一个external-modules"文件夹.

The files could really be declared in any folder however, it's good to put them together, in a directory that describes what they are. In our projects, we have a folder called "ambient-types" and within that we have an "external-modules" folder.

我读过我们可以声明一个模块,比如 redux-offline.d.ts

I've read that we can declare a module, something like redux-offline.d.ts

你说得对,这将位于 external-modules 文件夹中.

You're right, This would sit within the external-modules folder.

Typescript 如何知道该模块正在声明外部模块的接口?

How does Typescript know that that module is declaring the interface of an external module?

在您的 redux-offline.d.ts 文件中,我们声明了所谓的环境声明,如下所示:

In you're redux-offline.d.ts file we declare what's called an ambient declaration, it would look as follows:

declare module 'redux-offline';

redux-offline 现在可以从您自己的文件中导入.

redux-offline will now be available for import from your own files.

import { redux-offline } from 'redux-offline';

这基本上告诉 Typescript,在运行时您希望有一个名为 redux-offline 的文件/库可用.请注意,导入将具有任何"类型.

This basically tells Typescript that at runtime you expect that there will be a file/library called redux-offline available. Note that the import will have an "any" type.

环境声明是您对环境做出的承诺编译器.如果这些在运行时不存在并且您尝试使用它们,事情会毫无预​​兆地破裂.

Ambient declarations is a promise that you are making with the compiler. If these do not exist at runtime and you try to use them, things will break without warning.

更多参考见 - https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.htmlhttps://www.typescriptlang.org/docs/handbook/modules.html