I want to define several interfaces in their own file in my typescript-based project, from which I'll implement classes for production as well as mocks for testing. However, I can't figure out what the correct syntax is. I've found plenty of tutorials on declaring interfaces and implementing them, but they all have a trivial implementation of both the interface and derived classes in the same file, which isn't very real-world. What's the right way to export and import the interfaces?
You should put it in a separate file. That way it's easier to swap in a different implementation, or make the interfaces (the API of your system) available for others to code against without knowing the details of your implementation, or having to drag in related dependencies.
Use a named export to export an interface in TypeScript, e.g. export interface Person{} . The exported interface can be imported by using a named import as import {Person} from './another-file' . You can have as many named exports as necessary in a single file.
You need to export the interface from the file in which is defined and import it wherever you want to use it.
in IfcSampleInterface.ts
:
export interface IfcSampleInterface { key: string; value: string; }
In SampleInterface.ts
import { IfcSampleInterface } from './IfcSampleInterface'; let sampleVar: IfcSampleInterface;
Use definition (d.ts
) files and namespaces, no need to import/export modules this way. DefinitelyTyped project has guidance and huge number of examples how to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With