简体   繁体   中英

How to include typescript in javascript

I have a node.js with server.js

var http = require('http');
var port = process.env.port || 1337;
http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello World\n');
}).listen(port);

Say I have a typescript t.ts

var a = 123;
console.log(a);

I have two questions:

  1. Is it possible to call the t.ts from server.js (assume I must use server.js)?

  2. Is it possible to convert the server.js to server.ts (becomes a typescript)?

Normally this should be possible if your script exports a class or module. Wrap its functionality in a function, and export it in TS.

export function doThing() {
  var a = 123;
}

// server.js:
var doThing = require('t');

doThing();

TypeScript uses mostly JavaScript syntax so you can usually just rename the file to .ts and most of it will work, albeit with a few things having unknown types to start with. You may need to just replace the keyword var with import in your require() lines. I don't think there's an "automatic conversion" program though.

ad 1) No, node cannot process TypeScript scripts unless you compile t.ts to t.js first by the TypeScript compiler.

ad 2) TypeScript adds functionality to JavaScript and in many cases you can just rename file.js to file.ts and you will have valid TypeScript code but there are also cases when you'll get an error - for example:

  • Variable reuse

     var n = 5; // TypeScript compiler infers that 'n' is a number n = "a"; // Error: "a" is not a number! 
  • If you target browsers and you use window object then you may encounter the following error:

     var cropper = window.cropper; // throws error: Property 'cropper' does not exist on type 'Window' 

AFAIK there is no conversion tool because the previous examples show that the tool would struggle with error resolving. However, there are migration guides from people who went through the process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM