typescript 打字稿中的全局类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42984889/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:22:31  来源:igfitidea点击:

Global types in typescript

typescripttypescript-typings

提问by Tal

Is there a way to make a file in your typescript file that defines globally accessible types?

有没有办法在打字稿文件中创建一个定义全局可访问类型的文件?

I like typescript but find that when i want to be truly type safe I have to explicitly import types from all over the system. It's rather annoying.

我喜欢打字稿,但发现当我想要真正的类型安全时,我必须从整个系统中显式导入类型。比较烦人。

采纳答案by Sebastian Sebald

Yes this is possible. You can find all information here: https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html

是的,这是可能的。您可以在此处找到所有信息:https: //www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html

The important part is this:

重要的部分是这样的:

declare global {
    /*~ Here, declare things that go in the global namespace, or augment
     *~ existing declarations in the global namespace
     */
    interface String {
        fancyFormat(opts: StringFormatOptions): string;
    }
}

回答by Raid

A little late but, you can add a file.d.ts anywhere in your project as I've noticed, and it will be picked up.

有点晚了,但是,正如我所注意到的,您可以在项目中的任何位置添加 file.d.ts,它将被拾取。

For example, in my project I wanted a:

例如,在我的项目中,我想要一个:

Optional<T> = T | null;

And I didn't know where to add it, so I added a common.d.ts in a folder, and added:

而且我不知道在哪里添加,所以我在一个文件夹中添加了一个common.d.ts,并添加了:

declare type Optional<T> = T | null;

Now it's being picked up and no errors. Didn't even need to import it. This of course being tested in vscode, not sure if it will work in your editor.

现在它正在被拾取并且没有错误。甚至不需要导入它。这当然正在 vscode 中进行测试,不确定它是否可以在您的编辑器中工作。

(Depending on your file include/exclude rules of course, but most projects include all *.ts)

(当然取决于您的文件包含/排除规则,但大多数项目都包含所有 *.ts)