[英]Typescript and Node.JS combined
我有一個以某種方式用JavaScript編寫的工作的node.js服務器(不是我寫的),我決定使用Typescript重寫它,因為我是.NET。 有什么辦法可以與節點同時使用並保留類型嗎?
方法a) -構建成功,但是節點無法運行
文件PeripheryInstance.ts:
class PeripheryInstance {
Type: string;
PortName: string;
constructor(type: string, portName: string) {
this.Type = type;
this.PortName = portName;
}
myMethod(){
}
}
文件服務器
class Server{
static periphery: PeripheryInstance;
public static start() {
this.periphery = new PeripheryInstances("a", "b");
this.periphery.myMethod();
}
}
方法b) -成功構建,節點正在運行,但是我不能使用“ intellisense”(類型PeripheryInstance上的myMethod())並且代碼更難以閱讀
文件PeripheryInstance.ts:
module.exports = class PeripheryInstance {
Type: string;
PortName: string;
constructor(type: string, portName: string) {
this.Type = type;
this.PortName = portName;
}
myMethod(){
}
}
文件服務器
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();
}
}
我的問題是:是否可以將方法a)與node.js一起使用,以便可以使用所有類型代碼的特權? 還是我必須使用某種形式的方法b) ? 謝謝你
您需要為節點和正在使用的任何其他依賴庫npm install --save @types/node
: npm install --save @types/node
您還需要打字稿: npm install --save-dev typescript
然后,有很多教程可以正確地完成它。 這是我關注的內容: https : //blog.risingstack.com/building-a-node-js-app-with-typescript-tutorial/
除了您需要在運行輸出之前設置Typescript編譯之外,這沒有什么其他的。 不要在代碼中的any
地方使用any
類型,因為那樣會扼殺使用Typescript的目的,並且您將不會擁有Intellisense。 而是為每個方法和類使用正確的類型。
在方法A中,Node無法運行意味着什么? 您應該在構建后運行生成的輸出。 不是打字稿文件,而是JS文件。
在方法B中,存在一些錯誤。 您不應該執行module.exports
。 正確的方法是export class PeripheryInstance{}
。 另外, require
不是在Typescript中使用的正確方法。 請改用import
語法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.