简体   繁体   中英

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.

With internal modules, you could pull in the .ts reference at the top of your file and you were good to go. 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). 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.

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).

Go ahead and import them. TSC won't output import statements with things that are only used for type checking. Interfaces will just disappear from the resulting 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.

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.

Yes, I agree. I really recommend putting interfaces that are relevant to the module, in the module, and not scattered across the global scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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