HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptCritical

How to declare and import TypeScript interfaces in a separate file

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
typescripthowandseparatedeclareinterfacesfileimport

Problem

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;

Code Snippets

export interface IfcSampleInterface {
   key: string;
   value: string;
}
import { IfcSampleInterface } from './IfcSampleInterface';
let sampleVar: IfcSampleInterface;

Context

Stack Overflow Q#37263357, score: 218

Revisions (0)

No revisions yet.