【发布时间】:2017-08-16 12:42:22
【问题描述】:
有没有办法在你的 typescript 文件中创建一个定义全局可访问类型的文件?
我喜欢打字稿,但发现当我想要真正的类型安全时,我必须从整个系统中显式导入类型。比较烦人。
【问题讨论】:
标签: typescript typescript-typings
有没有办法在你的 typescript 文件中创建一个定义全局可访问类型的文件?
我喜欢打字稿,但发现当我想要真正的类型安全时,我必须从整个系统中显式导入类型。比较烦人。
【问题讨论】:
标签: typescript typescript-typings
是的,这是可能的。您可以在这里找到所有信息:https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html
重要的是:
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;
}
}
【讨论】:
ts(2669)。
我发现接受的答案不起作用(也许是一些需要完成的配置?)。所以经过一些修补,我让它为我工作(也许我也有一些奇怪的配置选项?让我知道它是否不起作用,我会删除这个答案)。
types/global.d.ts
tsconfig.json 并将"*": ["types/*.d.ts"] 包含在paths 下。 (如果您愿意,您还应该能够直接处理创建的文件)。declare global 或类似文件。现在您应该可以使用此文件中声明的类型了(使用 typescript 3.9.6 和 3.7.5 测试)。
示例文件:
// global.d.ts
declare interface Foo {
bar: string;
fooBar: string;
}
您的tsconfig 应该是什么样子:
[...]
"paths": {
"*": ["types/*.d.ts"]
},
[...]
【讨论】:
declare global,那就太好了。正如官方文档中所述。
paths 也需要一个 baseUrl,即使这样,似乎也没有办法让 typescript 拾取 d.ts 文件。它适用于 vscode 中的智能感知,但不适用于 tsc 编译器。
有点晚了,但是您可以在项目中的任何位置添加一个 file.d.ts,正如我所注意到的,它会被拾取。
例如,在我的项目中,我想要一个:
Optional<T> = T | null;
而且我不知道在哪里添加,所以我在一个文件夹中添加了一个common.d.ts,并添加:
declare type Optional<T> = T | null;
现在它正在被拾取并且没有错误。甚至不需要导入它。这当然是在 vscode 中测试的,不确定它是否可以在你的编辑器中工作。
(当然取决于您的文件包含/排除规则,但大多数项目都包含所有 *.ts)
【讨论】:
除了塞巴斯蒂安·塞巴尔德的回答
别忘了
export {}
这使它成为真正的模块。
就是这样。
这是有效的。
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;
}
}
export {}
【讨论】: