我正在尝试为此代码构建 typescript 定义文件(在 myscript.ts
中):
var rectangle = new Rectangle(new Point(20, 20), new Size(60, 60));
var path = new Path.Rectangle(rectangle);
path.strokeColor = 'black';
请注意,这里第一个 Rectangle 与第二个 Rectangle 是不同的类型 (Path.Rectangle
)。
这是我现在拥有的(在 myscript.d.ts
中):
declare class Point {
constructor(x: number, y: number);
add: (something: number[]) => Point;
}
declare class Size {
constructor(width: number, height: number);
}
declare class Rectangle {
constructor(point: Point, size: Size);
topLeft: Point;
bottomRight: Point;
}
declare module Path {
class PathBase {
strokeColor: string;
bounds: Rectangle; // <== here I need the Rectangle type defined outside of the Path module
fillColor: Color;
}
export class Rectangle extends PathBase {
constructor(point: Point, size: Size);
constructor(rec : Rectangle); // <== here I need the Rectangle type defined outside of the Path module
}
}
使用此定义,以下两行均失败:
var path = new Path.Rectangle(rectangle);
var upperLeft = path.bounds.topLeft;
我明白为什么,但不知道如何修改定义。感谢您的帮助。
最佳答案
根据@xmojmr 的评论,我找到了一个有效的定义:
我的第一次尝试:
declare class Rectangle {
constructor(point: Point, size: Size);
topLeft: Point;
bottomRight: Point;
}
变成:
declare class NumericRectangle { // <=================== renamed
constructor(point: Point, size: Size);
topLeft: Point;
bottomRight: Point;
}
declare class Rectangle extends NumericRectangle { // <=================== added
}
...和
declare module Path {
class PathBase {
strokeColor: string;
bounds: Rectangle; // <== here I need the Rectangle type defined outside of the Path module
fillColor: Color;
}
export class Rectangle extends PathBase {
constructor(point: Point, size: Size);
constructor(rec : Rectangle); // <== here I need the Rectangle type defined outside of the Path module
}
}
... 变成:
declare module Path {
class PathBase {
strokeColor: string;
bounds: NumericRectangle; // <=================== modified
fillColor: Color;
}
export class Rectangle extends PathBase {
constructor(point: Point, size: Size);
constructor(rec: NumericRectangle); // <=================== modified
}
}
关于javascript - typescript 定义 : same name but different types inside and outside module?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27252377/