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 classCirclethat has one member variable calledradiusand one methodgetArea(). They return the area of the circle for the givenradius. -
We export that
Circlewith the keywordexport default. -
Now, we create another file called
index.tswhere we import the classCirclefrom thecircle.tsfile with this statement:
import Circle from "./circle"
Here, we don’t need to mention the
.tsextension if it is a typescript file. -
At line
5in theindex.tsfile, we construct an objectc1from theCircleclass imported from thecircle.tsfile -
At line
8, we access thegetArea()method provided by Circle class to get an area for the Circle objectc1.
// exporting Circle classexport 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.
//import Circle class from circle.ts fileimport { Circle as RenamedCircle } from "./circle"// constructing c1 object from imported Circle classlet c1 = new RenamedCircle(5)//accesing area and printing it to consoleconsole.log(c1.getArea())