2017-08-23 23 views
0

我有一個工作node.js服務器以某種方式寫在JavaScript(這不是我寫的),我決定使用打字機重寫它,因爲我是.NET人。有什麼方法可以將它與節點一起使用並同時保留類型?Typescript和Node.JS合併

接近) - 成功的構建,但節點不能運行

文件PeripheryInstance.ts:

class PeripheryInstance { 
    Type: string; 
    PortName: string; 

    constructor(type: string, portName: string) { 
     this.Type = type; 
     this.PortName = portName; 
    } 

    myMethod(){ 

    } 
} 

文件Server.ts

class Server{ 
    static periphery: PeripheryInstance; 
    public static start() { 
     this.periphery = new PeripheryInstances("a", "b"); 
     this.periphery.myMethod(); 
    } 
} 

B方法) - 成功構建,節點正在運行,但我無法使用「智能感知」(myMethod()在類型PeripheryIns ,孟清湘)和代碼更難以閱讀

文件PeripheryInstance.ts:

module.exports = class PeripheryInstance { 
    Type: string; 
    PortName: string; 

    constructor(type: string, portName: string) { 
     this.Type = type; 
     this.PortName = portName; 
    } 

    myMethod(){ 

    } 
} 

文件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,所以我可以使用所有類型代碼的特權?或者我必須使用某種形式的方法b)?謝謝你。

回答

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語法。

相關問題