Answer the question
In order to leave comments, you need to log in
Why are Module and Namespace needed?
Good afternoon, what are modules and namespaces used for in ts ?
After all, js has modularity and we import everything we need explicitly, when importing, we give a unique name to everything that was imported.
For what purposes and cases can we use module, namespace ?
Answer the question
In order to leave comments, you need to log in
TypeScript appeared even before any modules appeared in the JavaScript on which it is based, not only native ones, even emulations like commonjs or amd did not exist then. In those days, it was normal to simply wrap the contents of the file in a closure, and then either simply load all the files through the script tag, or simply combine these files into one. Outside, one single variable was highlighted, containing the entire public api of such a module, it was placed either in a global object or in another such variable.
The module and namespace constructs allow you to simplify the creation of such variables, saving the developer from writing the same type of code. In this regard, they essentially do the same thing.
This is currently deprecated and the default eslint typescript plugin disallows these constructs.
The second use is for declaration files.
namespace allows you to declare an object, but somewhat special in terms of typing, it can contain any language entities and export some of them, including types, which is not available for a normal object type declaration.
declare namespace XXX {
// по сути просто поле XXX.a
let a: number;
// то же поле XXX.b но уже const
// современный ts позволяет делать поля readonly, но раньше так было нельзя
const b: number;
// функция, по сути метод XXX.c()
function c(): void;
// а вот вложенный тип через тип объекта не объявить, а в namespace можно
type T = number | string;
}
declare module '*.png' {
const url: string;
export default url;
}
declare module '*.css' {
const classNames: Record<string, string>;
export default classNames;
}
After all, js has modularity and we import everything we need explicitly, when importing, we give a unique name to everything that was imported.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question