Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and import typescript interfaces in a separate file

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?

like image 241
snort Avatar asked May 16 '16 21:05

snort


People also ask

Should interfaces be in a separate file?

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.

Can you export interfaces TypeScript?

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.


2 Answers

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; 
like image 150
Ajay Avatar answered Nov 04 '22 08:11

Ajay


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.

like image 24
Artem Koshelev Avatar answered Nov 04 '22 09:11

Artem Koshelev