Borislav Hadzhiev
Thu Mar 03 2022·3 min read
Photo by Dorothea Oldani
To import an interface from another file in TypeScript:
A
, e.g. export interface Employee {}
.B
as
import { Employee } from './another-file'
.B
.Here is an example of exporting an interface from a file called
another-file.ts
.
// 👇️ named export export interface Employee { id: number; name: string; salary: number; }
Here is how we would import the Employee
interface
in a file called index.ts
.
// 👇️ named import import { Employee } from './another-file'; const emp: Employee = { id: 1, name: 'James', salary: 100, }; console.log(emp);
Make sure to correct the path that points to the another-file
module if you
have to. The example above assumes that another-file.ts
and index.ts
are
located in the same directory.
For example, if another-file.ts
was located one directory up, you'd have to
import as import {Employee} from '../another-file'
.
TypeScript uses the concept of modules, in the same way that JavaScript does.
The example above uses a named export and a named import.
The main difference between named and default exports and imports is - you can have multiple named exports per file, but you can only have a single default export.
Let's look at an example of how we would import an interface that was exported using a default export.
Here are the contents of another-file.ts
.
// 👇️ default export export default interface Employee { id: number; name: string; salary: number; }
And here is how we would import the interface using a default import.
// 👇️ default import import Employee from './another-file'; const emp: Employee = { id: 1, name: 'James', salary: 100, }; console.log(emp);
Notice that we didn't wrap the import in curly braces.
We could have also used a different name when importing the interface, e.g.
Foo
.
// 👇️ default import import Foo from './another-file'; const emp: Foo = { id: 1, name: 'James', salary: 100, }; console.log(emp);
This works, but is confusing and should be avoided.
You can also mix and match. Here is an example of a file that uses both a default and a named export.
// 👇️ default export export default interface Employee { id: number; name: string; salary: number; } // 👇️ named export export interface Person { name: string; }
And here is how you would import the two interfaces.
// 👇️ default and named imports import Employee, { Person } from './another-file'; const emp: Employee = { id: 1, name: 'James', salary: 100, }; console.log(emp); const person: Person = { name: 'Alice', }; console.log(person);
We used a default import to import the Employee
interface and a named import
to import the Person
interface.
Note that you can only have a single default export per file, but you can have as many named exports as necessary.