Home > other >  Use typescript class in javascript
Use typescript class in javascript

Time:11-14

I've been going around the block in circles and just wanted an easy example of how I could use a typescript class in a javascript function.

My motivation is to use a typescript constant in a legacy js file (the js file can't be converted to ts yet, hence my dilemma).

I've read that .ts code should be somehow built in the process for us to be able to use it in .js, but everything has been a bit convoluted.

Example .ts class:

export class ExampleConstantsClass { static readonly exampleConst = 1; }

Now I'd like to import this in a .js file and use it for example like this:

function exampleFunction() { return ExampleConstantsClass.exampleConst }

CodePudding user response:

Your code usually can't be run as typescript. At some point it has to be compiled into JS in order to be run. Depending on your compiler settings you could maybe even just import from the compiled JS-file into your native JS file.

yourJSFile.js
tsFile.js (this is the file the compiler generates)

tsFile.ts (this is your ts file you write in)

you now just import from tsFile.js into yourJSFile.js (you need to compile your TS code anyways, otherwise you won't be able to actually run it)

As the comments pointed out, tsc is the compiler you usually use for Typescript. (There are tons of tutorials on how to do a basic tsc setup) - But may I ask how you managend to use TS without a compiler until now?

CodePudding user response:

I was able to compile your .ts code to a .js es6 module with this setup. Create a tsconfig.json file with these contents:

{
    "compilerOptions": {
        "module": "esnext",
        "target": "esnext"
    },
    "include": [
        "**/*.ts"
    ]
}

Then open a terminal in your project folder and type tsc.

  • Related