How to use Typescript files inside Javascript file?

Praveen David Mathew
3 min readJan 9

--

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
├── checkFile.ts
  1. create npm folder called demo_project , do npm init
  2. create a javascript file called start.js
  3. Now create a folder called typescript_files inside demo_project
  4. so all typescript_files will be inside this folder , create a typescript file called checkFile.ts (as given below)
  5. install following packages npm i @types/fs-extra fs-extra json5 ts-node typescript

checkFile.ts :

import fs from 'fs-extra'


let filePath: string = 'test'
/**
* Print a message on default import
* @returns {string} message
*/
export default function intro(): string {
return 'Welcome to demo project , this message is from typescript'
}

/**
* Does the file exists
* @returns {boolean} Whether file exists or not
*/
export function fileExist(): boolean {
return fs.existsSync(filePath)
}

--

--

Praveen David Mathew

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