How to use Typescript files inside Javascript file?

Praveen David Mathew
3 min readJan 9, 2023

Introduction:

Assume we have a javascript file called start.js , and we want to import the checkFile.ts into it. As typescript is superset of javascript , we cannot theoretically use typescript in javascript .

This limitation can be overcome using ts-node , a transpiler (ts to js converter)

ts-node can register the typescript file to be transpiled on runtime and there by allowing us to use the typescript file in JS file

so for using checkFile.ts , we create a index.js file which uses ts-node.register and then exports the typescript package .

This index.js file transforms the exported typescript to js in runtime.

Note: VScode understand the workflow so can do lazy loading or intellisence and make over life easier.

Now instead of importing the checkFile.ts in the start.js file , we imports index.js file . I

Index.js file exposes all the typescript methods and properties from checkFile.ts to start.js and hence we can use methods defined inside checkFile from start.js

Now lets try this out:

Demo Project :

initial structure:

├── package.json
├── start.js
└── typescript_files
├──…

--

--

Praveen David Mathew
Praveen David Mathew

Written by Praveen David Mathew

An open source advocator/WebdriverIO Projectcommiter/Postman Supernova/Postman-html-extra contributor/Stack overflow sqa moderator/Speaker

Responses (1)