如何在javascript中包含typescript

时间:2015-10-31 00:39:12

标签: javascript node.js typescript

我有一个带有server.js的node.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);

说我有打字稿t.ts

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

我有两个问题:

  1. 是否可以从t.ts调用server.js(假设我必须使用server.js)?

  2. 是否可以将server.js转换为server.ts(成为打字稿)?

2 个答案:

答案 0 :(得分:0)

通常,如果脚本导出类或模块,则应该可以这样做。将其功能包装在一个函数中,并将其导出到TS中。

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

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

doThing();

TypeScript主要使用JavaScript语法,因此您通常可以将文件重命名为.ts,并且大部分文件都可以使用,尽管有一些事情的类型未知。您可能只需要在require()行中将关键字var替换为import。我不认为有一个“自动转换”程序。

答案 1 :(得分:0)

ad 1)不,除非您首先通过TypeScript编译器将t.ts编译为t.js,否则节点无法处理TypeScript脚本。

ad 2)TypeScript为JavaScript添加了功能,在很多情况下,您只需将file.js重命名为file.ts即可获得有效的TypeScript代码,但也有一些情况下您会获得错误 - 例如:

  • 变量重用

    var n = 5;  // TypeScript compiler infers that 'n' is a number
    n = "a";    // Error: "a" is not a number!
    
  • 如果您定位浏览器并使用window对象,则可能会遇到以下错误:

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

AFAIK没有转换工具,因为前面的示例显示该工具很难解决错误。但是,完成此过程的人员中有migration guides