How modules, packages and type declaration files work in typescript
Let's create a simple math module, publish it to npm, create types for it, publish those types, and then demonstrate how to use the module.
Step 1: Create the Math Module
-
Initialize the project:
mkdir simple-math-module cd simple-math-module npm init -y
-
Create the module file:
Create a file named
index.js
with the following content:// index.js function add(a, b) { return a + b; } function subtract(a, b) { return a - b; } module.exports = { add, subtract };
-
Update
package.json
:Update the
main
field inpackage.json
to point toindex.js
:{ "name": "simple-math-module", "version": "1.0.0", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "A simple math module for learning purposes" }
-
Publish the module:
First, login to npm:
npm login
Then, publish the module:
npm publish
Step 2: Create Type Definitions
-
Create a new directory for type definitions:
mkdir types cd types npm init -y
-
Create the type definition file:
Create a file named
index.d.ts
with the following content:// index.d.ts export function add(a: number, b: number): number; export function subtract(a: number, b: number): number;
-
Update
package.json
:Update the
main
field inpackage.json
to point toindex.d.ts
and add atypes
field:{ "name": "@types/simple-math-module", "version": "1.0.0", "main": "index.d.ts", "types": "index.d.ts", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "description": "Type definitions for simple-math-module" }
-
Publish the type definitions:
npm publish
Step 3: Using the Module
-
Create a new project:
mkdir math-module-usage cd math-module-usage npm init -y
-
Install the math module and its types:
npm install simple-math-module npm install --save-dev @types/simple-math-module
-
Create a TypeScript file to use the module:
Create a file named
index.ts
with the following content:// index.ts import { add, subtract } from 'simple-math-module'; const sum = add(10, 5); const difference = subtract(10, 5); console.log(`Sum: ${sum}`); console.log(`Difference: ${difference}`);
-
Compile and run the TypeScript file:
Install TypeScript:
npm install --save-dev typescript
Create a
tsconfig.json
file:{ "compilerOptions": { "module": "commonjs", "target": "es6", "outDir": "./dist", "strict": true }, "include": ["index.ts"] }
Compile the TypeScript file:
npx tsc
Run the compiled JavaScript file:
node dist/index.js