简体   繁体   English

如何在 TypeScript 中使用带有“declare”关键字的导入?

[英]How to use import with “declare” keyword in TypeScript?

I have a d.ts file with a variable declaration, like this:我有一个带有变量声明的 d.ts 文件,如下所示:

declare var $: () => SomeValue;

And it is works good, in other places i can use this variable without import.而且效果很好,在其他地方我可以在不导入的情况下使用这个变量。

But, when i add some import from another module, this variable is not visible from other code.但是,当我从另一个模块添加一些导入时,这个变量在其他代码中是不可见的。

import { SomeValue } from "./SomeModule";
declare var $: () => SomeValue;

What the syntax for this need?这个需要什么语法?

When .d.ts files use export or import , they become treated as a module instead of as ambient typings ..d.ts文件使用exportimport时,它们被视为module而不是环境typings

However you can still add to the global namespace using declare global .但是,您仍然可以使用declare global添加到全局命名空间。 This allows you to augment global types, and even add new global types:这允许您扩充全局类型,甚至添加新的全局类型:

.d.ts .d.ts

import { SomeValue } from "./SomeModule";

declare global {
    interface Window {
        $: () => SomeValue;
    }
    interface SomeGlobalInterface {
        x: number;
    }
}

.ts .ts

// () => SomeValue
window.$

let value!: SomeGlobalInterface;
value.x;

You'll need to add "export" keyword to the variable.您需要将“export”关键字添加到变量中。

export declare var $: () => SomeValue;

If you want this variable to only be available in the same file, then it is not necessary to add "export" keyword.如果您希望此变量仅在同一文件中可用,则无需添加“export”关键字。 However, if you want it to be used in other files, then you'll need to add "export" keyword.但是,如果您希望它在其他文件中使用,则需要添加“export”关键字。

The same goes for constants, functions and classes.常量、函数和类也是如此。 Adding "export" to it will make it available to be imported by other files.向其中添加“导出”将使其可供其他文件导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM