How to import another TypeScript file

Overview

Even though dividing code into modules is the best practice, it is problematic in TypeScript to import the files that are needed until TypeScript version 1.6.

Previously, we needed to use comment style reference, where we provide reference on top of the present file for other files.


/// <reference path="otherfile.ts"/>

class bar extends otherfile.foo { }

From TypeScript version 1.7, however, we can simply use import statements just like we use in es6.


import user from "./user.ts"

We must provide an export statement in other files for the things we want to expose, so we can import them in other files.

Example 1

In the following example:

  • We create a file called circle.ts. It contains a class Circle that has one member variable called radius and one method getArea(). They return the area of the circle for the given radius.

  • We export that Circle with the keyword export default.

  • Now, we create another file called index.ts where we import the class Circle from the circle.ts file with this statement:


    import Circle from "./circle"
    

    Here, we don’t need to mention the .ts extension if it is a typescript file.

  • At line 5 in the index.ts file, we construct an object c1 from the Circle class imported from the circle.ts file

  • At line 8, we access the getArea() method provided by Circle class to get an area for the Circle object c1.

index.ts
circle.ts
// exporting Circle class
export default class Circle{
radius:number;
constructor(radius:number){
this.radius = radius;
}
getArea(){
return 2 * 3.14 * this.radius;
}
}

Example 2

We can rename the imported classes, functions, or variables with as while importing.

In the following example, we import Circle as RenamedCircle using { Circle as RenamedCircle } in the import statement.


The explanation for this example is the same as the above example.

index.ts
circle.ts
//import Circle class from circle.ts file
import { Circle as RenamedCircle } from "./circle"
// constructing c1 object from imported Circle class
let c1 = new RenamedCircle(5)
//accesing area and printing it to console
console.log(c1.getArea())

Free Resources