Currently studying Typescript and delving into namespacing, import
, and export
.
During the creation of my first project, I realized that some classes were accessible in other files even without the export
keyword. Yet, a class with an import required export/import to be accessed elsewhere.
Why does this happen? Is it acceptable practice? When exactly is using export
mandatory, and when can it be omitted?
I initially believed that all classes and modules had to be export
/import
, but surprisingly, the code still runs smoothly without them.
class CoordinateModel {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
In another file, it can be utilized like so:
import * as d3 from "d3";
module Mouse {
export function getMousePosition(container:d3.ContainerElement): CoordinateModel {
var m = d3.mouse(container);
return new CoordinateModel(m[0], m[1]);
}
export function showMousePositionInElement(elementClassName: string, container: d3.ContainerElement) {
var m = Mouse.getMousePosition(container);
d3.select("." + elementClassName).html(m.x + ", " + m.y);
}
}
export = Mouse;