2013-05-21 36 views
0

我們在VS2012中創建了一個類型腳本項目,並定義了打字稿的界面。然後我們添加接口的實現和一些業務邏輯來使用接口。在VS中,我們將項目編譯爲打字稿的定義文件。描述文件中存在編譯錯誤,我們檢查錯誤並確定該接口未包含在項目的描述文件中。如何將界面包含在由VS2012生成的定義文件中for typesctipt

我們的問題: 當我們將多個TypeScript文件編譯爲一個文件時,是否可以將接口包含到TypeScript的描述文件中?

+0

「在我們VS編譯項目進入了打字稿定義文件」下面你爲什麼要編寫一個定義文件?定義文件通常保留在TypeScript中,它們不會被編譯爲JS。 – JcFx

回答

2

從你的問題我做出以下假設。

  • 您正在編譯使用--out標誌得到一個輸出文件
  • 您正在生成使用--declaration標誌定義您的打字稿
  • 你有一個文件和一個接口在另一個文件中實現

如果是這樣,你的界面應該出現在聲明文件中。這是一個例子。

示例代碼

InterfaceFile。TS

// Interface 
interface IPoint { 
    getDist(): number; 
} 

ImplementationFile.ts

/// <reference path="InterfaceFile.ts" /> 

// Module 
module Shapes { 

    // Class 
    export class Point implements IPoint { 
     // Constructor 
     constructor (public x: number, public y: number) { } 

     // Instance member 
     getDist() { return Math.sqrt(this.x * this.x + this.y * this.y); } 

     // Static member 
     static origin = new Point(0, 0); 
    } 
} 

app.ts

/// <reference path="ImplementationFile.ts" /> 

// Local variables 
var p: IPoint = new Shapes.Point(3, 4); 
var dist = p.getDist(); 

彙編和輸出

如果我編譯此示例程序使用下面的命令:

tsc --out mylib.js --declaration app.ts 

我得到mylib.d.ts

interface IPoint { 
    getDist(): number; 
} 
module Shapes { 
    class Point implements IPoint { 
     public x: number; 
     public y: number; 
     constructor(x: number, y: number); 
     public getDist(): number; 
     static origin: Point; 
    } 
} 
var p: IPoint; 
var dist: number; 
+0

我發現我有這個問題,並使其工作。我們使用TypeScript進行一些測試,例如使用多個項目來管理打字稿。謝謝。 –

0

我認爲你在你的csproj文件中定義了<TypeScriptOutFile>something.js</TypeScriptOutFile><TypeScriptGeneratesDeclarations>true</TypeScriptGeneratesDeclarations>。對於我的TypeScript 0.8.3.1版本(我假設0.9),包含文件(而不是.d.ts文件)引用的任何接口也將包含在內。只需在其中一個文件中添加對缺失接口的引用並重新編譯即可。該參考文件不必實際用於該文件。

4

也可以使用.ts而不是.d.ts作爲接口聲明文件。

您可以在這裏看到一個樣本:https://github.com/basarat/ts-test/tree/master/tests/compileToSingle

out.d.tshttps://github.com/basarat/ts-test/blob/master/tests/compileToSingle/out.d.ts包含dec公司接口.TShttps://github.com/basarat/ts-test/blob/master/tests/compileToSingle/dec.ts

out.d .ts不包含接口:https://github.com/basarat/ts-test/blob/34eeb54618e57765ea0e2f9ce0c48ebd7f46942a/tests/compileToSingle/out.d.ts 如果我有一個十二。 d.tshttps://github.com/basarat/ts-test/blob/34eeb54618e57765ea0e2f9ce0c48ebd7f46942a/tests/compileToSingle/dec.d.ts

您可以使用關鍵字聲明爲只申報任何物品,即:

declare class C{ 

} 

,而不是

class C{ 

} 

接口將保持他們的方式是和不使用這些declare關鍵字。

相關問題