Search code examples
typescripttypescript1.8

How to declare and import TypeScript interfaces in a separate file


I want to define several interfaces in their own files in my TypeScript project, from which I'll implement classes for production as well as mocks for testing.

However, I can't figure out the correct syntax. 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?


Solution

  • 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;