Namespaces and modules versus typing in typescript?

Can someone please explain the difference between these concepts with an example, am I really confused that using three of them when they all serve the same purpose?

+4
source share
1 answer

TL DR

Modules and namespaces are two means of encapsulation - breaking code into pieces that make sense. New code should be written using modules, not namespaces.

( "" ) , , , .., - . TypeScript , , , .

. DefinitelyTyped foo-bar @types/foo-bar npm.

Namespaces

JavaScript. IIFE, . "" , () , $ _ - .

:

namespace foo {
    export var x = 10;
    export var y = 20;
}

var foo;
(function (foo) {
    foo.x = 10;
    foo.y = 20;
})(foo || (foo = {}));

, , , . , : API (, $, _, angular) ...

ECMAScript ( JavaScript), CommonJS (i.e. Node.js), AMD ( Require.js) System.js. , , , , .

(CommonJS, AMD, System.js) : , , .

TypeScript , ECMAScript export. , TypeScript, import export .

,

export var x = 10;
export var y = 20;

CommonJS:

"use strict";
Object.defineProperty(module.exports, "__esModule", { value: true });
module.exports.x = 10;
module.exports.y = 20;

, .

/

"" (.d.ts ) , @types ( )

"" .

, Typings. TypeScript npm . , - , , , , "typings".

:

(.d.ts , ) TypeScript , . .ts --declaration, JavaScript.

, . , TypeScript:

function foo(x: number, y: number) {
    return x * 100 + y;
}

:

declare function foo(x: number, y: number): number

JavaScript, , , .

, JavaScript- TypeScript. , DefinitelyTyped.

DefinitelyTyped

git, 3000 . .

GitHub.

@types npm

DefinitelyTyped. , .d.ts lodash,

npm install @types/lodash

?

, . TypeScript. , , , , .

, , . TypeScript, , .

, - -, , JS, .

TypeScript, .js, .d.ts, .

, , ,

+15

Source: https://habr.com/ru/post/1679027/


All Articles