简体   繁体   English

使用外部模块时如何正确使用TypeScript接口?

[英]How do I use TypeScript Interfaces correctly when using External Modules?

I am somewhat new to external modules. 我对外部模块有些陌生。 I want to create a new Updatable interface which many of my game objects will implement. 我想创建一个新的Updatable接口,许多游戏对象都将实现该接口。

With internal modules, you could pull in the .ts reference at the top of your file and you were good to go. 使用内部模块,您可以在文件顶部插入.ts引用,这很好。 Blah implements Updatable

With external modules though, I cannot seem to figure out the process of how to write and access that interface. 但是,对于外部模块,我似乎无法弄清楚如何编写和访问该接口的过程。 I feel I do not want to import it because it is not a JS thing at the same time exporting it on the global scope does not make it accessible (Cannot find Updatable). 我觉得我不想导入它,因为它不是JS东西,同时在全局范围内导出它并不能访问它(找不到可更新)。 The only other suggestion I found on the internet was that someone was using d.ts files as interfaces which seems weird as I thought they were for definition files. 我在互联网上发现的唯一其他建议是,有人使用d.ts文件作为接口,这似乎很奇怪,因为我认为它们是用于定义文件的。

Can anyone shed light on the best way to do this? 谁能阐明实现此目标的最佳方法?

After some more digging I arrived on this ticket . 经过一番挖掘之后,我拿到了这张票

interface I {

}

export default I;

I feel I do not want to import it because it is not a JS thing at the same time exporting it on the global scope does not make it accessible (Cannot find Updatable). 我觉得我不想导入它,因为它不是JS东西,同时在全局范围内导出它并不能访问它(找不到可更新)。

Go ahead and import them. 继续并导入它们。 TSC won't output import statements with things that are only used for type checking. TSC不会输出仅用于类型检查的内容的import语句。 Interfaces will just disappear from the resulting JavaScript. 接口只会从生成的JavaScript中消失。

This code: 这段代码:

import {FooClass, BarInterface, BazClass} from './baz';

class Bam extends FooClass {
    boom(baz: BazClass): BarInterface { return {}; }
}

Will become the code below, if you target ES6. 如果您定位到ES6,它将成为下面的代码。

import { FooClass } from './baz';

class Bam extends FooClass {
    boom(baz) { return {}; }
}

The only other suggestion I found on the internet was that someone was using d.ts files as interfaces which seems weird as I thought they were for definition files. 我在互联网上发现的唯一其他建议是,有人使用d.ts文件作为接口,这似乎很奇怪,因为我认为它们是用于定义文件的。

Yes, I agree. 是的我同意。 I really recommend putting interfaces that are relevant to the module, in the module, and not scattered across the global scope. 我真的建议将与模块相关的接口放入模块中,并且不要将其分散在全局范围内。

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

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