Typescript
Installation
1. Verify Node.js Installation
You already installed Node.js from the official website. Let's check if it's properly installed:
node -v
npm -vThis should return version numbers. If not, try reinstalling Node.js.
2. Install TypeScript & ts-node
Since you installed TypeScript via Homebrew, it's system-wide. But projects should have their own local dependencies. Install TypeScript and ts-node locally:
npm install --save-dev typescript ts-node @types/nodeTo check if it's installed:
npx ts-node --version3. Initialize TypeScript Configuration (tsconfig.json)
Run:
npx tsc --initThis generates a tsconfig.json file. Modify it for a clean setup:
{
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
},
"include": ["src"],
"exclude": ["node_modules"]
}4. Project File Structure
A good structure for a TypeScript project:
my-ts-project/
│── src/
│ ├── index.ts
│── dist/ (Generated JS files)
│── node_modules/
│── package.json
│── tsconfig.json
│── .gitignoreRun:
mkdir src
touch src/index.ts
echo "console.log('Hello TypeScript!');" > src/index.ts5. Running TypeScript Code
Use ts-node to run TypeScript directly:
npx ts-node src/index.tsTo compile and run via Node:
npx tsc
node dist/index.js6. Adding Scripts for Convenience
Modify package.json:
"scripts": {
"dev": "ts-node src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}Now, you can run:
npm run dev # Run TypeScript directly
npm run build # Compile to JavaScript
npm start # Run compiled JS7. (Optional) Installing nodemon for Auto-Restart
For auto-reloading:
npm install --save-dev nodemonModify package.json:
"scripts": {
"dev": "nodemon --ext ts --exec ts-node src/index.ts"
}Run:
npm run devNow, changes in .ts files auto-restart the app.
Code
1. Simple Function Conversion
JavaScript:
function add(a, b) {
return a + b;
}TypeScript:
function add(a: number, b: number): number {
return a + b;
}Explanation:
In the TypeScript version, each parameter (a and b) is explicitly typed as a number, and the return type is also declared as number.
2. Using Interfaces for Object Shapes
JavaScript:
const person = {
name: "John",
age: 30
};TypeScript:
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "John",
age: 30
};Explanation:
An interface named Person is defined to describe the shape of the object. The variable person is then annotated with the Person interface.
3. Function with Object Parameter
JavaScript:
function greet(person) {
console.log("Hello " + person.name);
}TypeScript:
interface Person {
name: string;
age?: number; // Optional property
}
function greet(person: Person): void {
console.log("Hello " + person.name);
}Explanation:
The function parameter is typed using the Person interface. Here, age is marked as optional with the ?, and the function return type is declared as void since it doesn't return a value.
4. Converting a Class
JavaScript:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a noise.");
}
}TypeScript:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
speak(): void {
console.log(this.name + " makes a noise.");
}
}Explanation:
TypeScript requires that class properties like name are declared with a type. The constructor and methods also include type annotations for their parameters and return types.
5. Arrow Function Conversion
JavaScript:
const multiply = (a, b) => a * b;TypeScript:
const multiply = (a: number, b: number): number => a * b;Explanation:
The arrow function parameters are annotated as numbers and the return type is declared, ensuring type safety.
By adding these type annotations and interfaces, you gain better code clarity, improved error checking during compilation, and enhanced IDE support. These examples illustrate common patterns you can apply to gradually convert and improve your JavaScript projects with TypeScript.