How to import a function or its return value from typescript (.ts) to javascript (.js)

Viewed 872

I have a typescript file

a.component.ts

import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class DataService {
  constructor(private httpCLient: HttpClient) { }
  currentCode;
  setCurrentCode(code){
    this.currentCode = code;
  }
  getCurrentCode(){
    return this.currentCode;
  }
}

And I have a JavaScript file.

where I need to get value from the above typescript file.

Actually I need to get value from the getCurrentCode() function of above typescript and print it inside a JavaScript file.

So what I need to write inside my b.js file? how can I import the above file? Also I need to get value from the above function and write it inside my JavaScript file?

1 Answers

On Node, you can just require what you need from the Typescript file in the usual way. Basically you can think of the Typescript file as Javascript, the two are completely interoperable, it's just that you need to transpile it to JS using tsc before it will run on Node.

For example, in your JS file, you can just do something like the following

// Note, this assumes you've transpiled a.component.ts
// to a file called a.component.js (in the same directory)
const { DataService } = require('./a.component') 

const myDataService = new DataService(...)
Related