How to declare and import typescript interfaces in a separate file

snort picture snort · May 16, 2016 · Viewed 92.9k times · Source

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?

Answer

Ajay picture Ajay · May 17, 2016

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;