我想弄清楚如何以编程方式将打字稿文件呈现为 javascript 文件。
这是否可以与 ts-node 一起使用,例如:
function tsMiddleware (req, res, next) {
var parsed = require('url').parse(req.url);
if (parsed.pathname.match(/\.ts$/)) {
return ts(parsed.pathname).then(function (o) {
res.setHeader('Content-Type', 'text/js');
res.end(o.js);
}).catch((err) => {
console.log(err);
});
}
next();
function ts(src) {
return new Promise((resolve, reject) => {
require('ts-node').render({
file: 'src' + src
}, function (err, res) {
if (err) {
reject(err);
} else {
resolve(res);
}
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
我不想在 nodejs 中执行 ts 文件,而只是编译 ts 文件并将输出发送回浏览器。
我刚接触打字稿,最近正在写一门课。不幸的是,我的编辑器(Visual Studio Code)使我烦恼我无法理解的错误。它说:“对象(foo)可能是未定义的”。但是如何?
这是一个例子:
export class Foo {
foo: string | undefined;
constructor() {
this.foo = "hello";
}
lengthOfFoo() {
/*if (!this.foo) {
return;
}*/
let len = this.foo.length; // <- error: the object (foo) is possible undefined
return len;
}
}
Run Code Online (Sandbox Code Playgroud)
仅当我取消注释以上检查时,错误才会消失,但是由于构造函数:
constructor() {
this.foo = "hello";
}
Run Code Online (Sandbox Code Playgroud)
this.foo不能是不确定的,并且如果流程正确或我错了,那么错误应该不会首先出现。
为了解释为什么我使用这个表达式
foo: string | undefined;
Run Code Online (Sandbox Code Playgroud)
这只是一个简化的示例。我实际上是在尝试使用具有Map.get()函数(可能是未定义)的Map Type。这里是地图类型的声明:
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: …Run Code Online (Sandbox Code Playgroud)