我们在VS2012中创建一个类型脚本项目,并定义typescript的接口。然后我们添加接口的实现和一些业务逻辑来使用接口。在VS中,我们将项目编译为typescript的定义文件。并且描述文件中存在编译错误,我们检查错误并且接口没有包含在项目的描述文件中。
我们的问题: 当我们将多个TypeScript文件编译成一个文件时,是否可以将接口包含在TypeScript的描述文件中?
答案 0 :(得分:4)
也可以使用.ts
代替.d.ts
作为接口声明文件。
您可以在此处查看示例:https://github.com/basarat/ts-test/tree/master/tests/compileToSingle
我的 out.d.ts https://github.com/basarat/ts-test/blob/master/tests/compileToSingle/out.d.ts包含dec .ts 的界面: https://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 如果我有一个dec。 d.ts :https://github.com/basarat/ts-test/blob/34eeb54618e57765ea0e2f9ce0c48ebd7f46942a/tests/compileToSingle/dec.d.ts
您可以对任何仅声明的项目使用declare关键字,即:。
declare class C{
}
而不是
class C{
}
接口将保持原样,不要使用declare关键字。
答案 1 :(得分:2)
从你的问题我做出以下假设。
--out
标志编译TypeScript以获取单个输出文件--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;
答案 2 :(得分:0)
我认为你在csproj文件中定义了<TypeScriptOutFile>something.js</TypeScriptOutFile>
和<TypeScriptGeneratesDeclarations>true</TypeScriptGeneratesDeclarations>
。从TypeScript版本0.8.3.1开始(我假设为0.9)也将包含从包含文件(而不是.d.ts文件)引用的任何接口。只需在其中一个文件中添加对缺少的接口的引用并重新编译即可。该引用不必实际用于该文件。