我有一个工作的node.js服务器以某种方式用javascript编写(这不是我写的)我决定使用typescript重写它,因为我是.NET家伙。有没有办法将它与节点一起使用并同时保留类型?
接近a) - 成功构建,但节点无法运行
File PeripheryInstance.ts:
class PeripheryInstance {
Type: string;
PortName: string;
constructor(type: string, portName: string) {
this.Type = type;
this.PortName = portName;
}
myMethod(){
}
}
File Server.ts
class Server{
static periphery: PeripheryInstance;
public static start() {
this.periphery = new PeripheryInstances("a", "b");
this.periphery.myMethod();
}
}
方法b) - 成功构建,节点正在运行,但我不能使用“intellisense”(类型为PeripheryInstance的myMethod())并且代码更难以阅读
File PeripheryInstance.ts:
module.exports = class PeripheryInstance {
Type: string;
PortName: string;
constructor(type: string, portName: string) {
this.Type = type;
this.PortName = portName;
}
myMethod(){
}
}
File Server.ts
var pi = require('./PeripheryInstance');
class Server{
// pi.PeripheryInstance return (TS) cannot find namespace pi
static periphery: any;
public static start() {
this.periphery = new pi.PeripheryInstances("a", "b");
// myMethod is not suggested by intellisence, because this.periphery is "any"
this.periphery.myMethod();
}
}
我的问题是:有没有办法在node.js上使用方法a),所以我可以使用所有类型代码的特权?或者我必须使用某种形式的方法b)?谢谢你。
答案 0 :(得分:1)
您需要为节点和您正在使用的任何其他依赖库安装类型:npm install --save @types/node
您还需要打字稿:npm install --save-dev typescript
然后有很多教程以正确的方式完成它。这是我所遵循的:https://blog.risingstack.com/building-a-node-js-app-with-typescript-tutorial/
除了在运行输出之前需要设置Typescript编译之外,世界上什么都没有。不要在代码中的任何位置使用any
类型,因为这样会破坏使用Typescript的目的,并且您不会使用Intellisense来实现它。而是为每个方法和类使用适当的类型。
在方法A中,Node是什么意思不能运行它?您应该在构建后运行生成的输出。不是打字稿文件,而是JS文件。
在方法B中,存在一些错误。你不应该module.exports
。例如,正确的方法是export class PeripheryInstance{}
。此外,require
不是在Typescript中使用的正确方法。请改用import
语法。