有一个npm模块one-two-three
例如。
里面有TS文件index.ts
(主要)和functions.ts
.
函数.ts:
export interface IPoint {
x: number;
y: number;
}
export function sum(a: IPoint, b: IPoint): IPoint {
return {
x: a.x + b.x,
y: a.y + b.y
};
}
索引.ts:
import functions = require("./functions");
export var sum: typeof functions.sum = functions.sum;
compile:
tsc --module commonjs --declaration index.ts
文件已创建:index.js
, index.d.ts
, functions.js
and functions.d.ts
.
Ok.
还有一个依赖的库one-two-three
.
npm install --save one-two-three
我想包含依赖项并使用它和接口functions.ts
.
import mo = require("one-two-three");
Error Cannot find external module 'one-two-three'
.
/// <reference path="node_modules/one-two-three/index.d.ts" />
import mo = require("one-two-three");
没有反应。
import mo = require("./node_modules/one-two-three");
Fail.
declare var require;
var mo = require("one-two-three");
它编译成功。
但没有类型检查。
可以写:mo.unknownFunction()
它将被编译。
无法使用接口。
如何使上述描述正确?
UPDATE
我已经实现了预期的行为如下。
编辑 d.ts 文件。
函数.d.ts:
declare module "one-two-three.functions" {
export interface IPoint {
x: number;
y: number;
}
export function sum(a: IPoint, b: IPoint): IPoint;
}
索引.d.ts:
/// <reference path="./functions.d.ts" />
declare module "one-two-three" {
import functions = require("one-two-three.functions");
export var sum: typeof functions.sum;
}
使用它:
/// <reference path="node_modules/one-two-three/index.d.ts" />
/// <reference path="node_modules/one-two-three/functions.d.ts" />
import oneTwoThree = require("one-two-three");
import functions = require("one-two-three.functions");
import IPoint = functions.IPoint;
function delta(a: IPoint, b: IPoint): number {
var dx: number = a.x - b.x,
dy: number = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}
var point1: IPoint = {x: 10, y: 20},
point2: IPoint = {x: 5, y: 5};
console.log(oneTwoThree.sum(point1, point2));
console.log(delta(point1, point2));
成功。
但我们必须履行双重职责。
编写代码并单独描述接口。
有没有办法生成正确的 d.ts?
问题是 d.ts 应该使用内部语法来描述模块(module {}
)。
但源文件是CommonJS模块。
它没有该部分module
.