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.jswith 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
mainfield inpackage.jsonto 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 loginThen, 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.tswith 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
mainfield inpackage.jsonto point toindex.d.tsand add atypesfield:{ "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.tswith 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 typescriptCreate a
tsconfig.jsonfile:{ "compilerOptions": { "module": "commonjs", "target": "es6", "outDir": "./dist", "strict": true }, "include": ["index.ts"] }Compile the TypeScript file:
npx tscRun the compiled JavaScript file:
node dist/index.js