πŸš€Getting Started with TypeScript

Lay a solid foundation by understanding what TypeScript is, why it exists, and how it enhances JavaScript development.

πŸ“¦ Introduction to TypeScript

Welcome to TypeScript! If you've been programming with JavaScript but ever felt like it's missing something, TypeScript is here to help. It adds a layer of static typing to JavaScript, giving you more control and catching errors early in your development process.

πŸ’‘ What is TypeScript?

TypeScript is a superset of JavaScript that introduces static types. It compiles down to vanilla JavaScript and runs anywhere JavaScript can run.

  • TypeScript adds a layer of safety by catching errors at compile-time, not runtime.
  • It's supported by major IDEs with features like code completion and error highlighting.
  • The TypeScript community is thriving with excellent tooling and documentation.
// JavaScript
let age = 25;
age = 'twenty-five';

// TypeScript
let age: number = 25;
age = 'twenty-five'; // This line will throw an error

βœ… Why Use TypeScript?

  • Improved developer experience with better tooling and autocompletion.
  • Catching errors early in the development process.
  • Better code maintainability and scalability.
  • Stronger typing makes code more readable and self-documenting.

πŸ’‘ Key TypeScript Features

  • Static Typing: Define types for variables, function parameters, and return values.
  • Interface: Define shapes of objects and data structures.
  • Type Inference: TypeScript automatically determines the type based on usage.
  • Generics: Create reusable components that work with any type.
interface User {
  id: number;
  name: string;
  age?: number;
}

const createUser = (data: Omit<User, 'id'>): User => ({
  id: Date.now(),
  ...data
});

❌ Common TypeScript Pitfalls

  • Overusing types can make code overly verbose.
  • Misusing any type defeats the purpose of static typing.
  • Ignoring compiler errors and warnings leads to unexpected bugs.
function multiply(x: number, y: number) {
  return x * y;
}

multiply('5', '10'); // TypeScript will throw an error here

βš™οΈ Setting Up Your Environment

Welcome to Setting Up Your Environment! This section will guide you through creating a TypeScript development environment from scratch. Let's get started on your journey to mastering NestJS with TypeScript.

  • Install Node.js and npm (if not already installed)
  • Set up a TypeScript project structure
  • Configure tsconfig.json for your project
  • Use popular editors like VSCode for TypeScript development

πŸ’‘ Getting Started with TypeScript

To work with TypeScript, you'll need to install Node.js and npm if they're not already installed on your system. Once Node.js is installed, you can use npm to install TypeScript globally.

# Install TypeScript globally
npm install -g typescript

βœ… Creating a Project Structure

Organize your project with the following directory structure:

/your-project
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ domain/
β”‚   └── infrastructure/
β”œβ”€β”€ test/
β”œβ”€β”€ .gitignore
β”œβ”€β”€ package.json
└── tsconfig.json

πŸ’‘ Configuring TypeScript

The `tsconfig.json` file is essential for configuring your TypeScript project. Here's a basic configuration:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true
  },
  "include": [
    "**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts"
  ]
}

βœ… Using TypeScript with VSCode

  • Install the TypeScript extension in VSCode (already included by default)
  • Set up your project structure as shown above
  • Use shortcuts like ⌘/Ctrl + Space for type hints and suggestions
// Run TypeScript compiler
npx tsc -w

// Build script example (package.json)
{
  "scripts": {
    "build": "tsc && cp src/tsconfig.json dist/tsconfig.json"
  }
}

❌ Common Mistakes to Avoid

  • Don't forget to add `tsconfig.json` and `package.json` to your `.gitignore` file
  • Avoid overwriting existing configuration files
  • Don't skip setting up proper compiler options for your project
  • Never commit node_modules to version control

βœ… Best Practices

  • Use `tsconfig.json` to configure compiler options consistently across your team
  • Keep your dependencies up to date by regularly running `npm update`
  • Write clean, well-formatted code using TypeScript's type system
  • Always test your configuration in development before production

πŸ“„ Writing Your First TypeScript File

Welcome to your first adventure in TypeScript! Today, we'll guide you through creating, compiling, and running your very first TypeScript file. Get ready to take your JavaScript skills to the next level with type safety and better development practices.

πŸ’‘ Setting Up Your Project

  • Ensure Node.js (v12+) and npm are installed on your system.
  • Open your terminal and run: npm install -g typescript to install TypeScript globally.
  • Create a new folder for your project and navigate into it.

βœ… Creating Your First TypeScript File

// Save this as example.ts

const message: string = "Hello, TypeScript!";
console.log(message);

Here's what's happening in our first file: - We declare a variable message with an explicit type string. - We assign it the value "Hello, TypeScript!". - Finally, we log it to the console.

βœ… Compiling and Running Your File

  • Run tsc example.ts to compile your file. This will create a compiled JavaScript version (example.js).
  • Execute the compiled code with node example.js.
  • To watch for changes and automatically recompile, use tsc --watch.

πŸ’‘ Understanding tsconfig.json

The tsconfig.json file is your project's configuration hub. It controls how TypeScript compiles your code. Here are some key options: - compilerOptions: Main settings like output directory, target version, and type checking behavior.

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src"
  }
}

πŸ’‘ Basic TypeScript Syntax Differences

  • Type annotations allow you to specify variable types: let age: number = 25;
  • Union types let variables accept multiple types: let status: string | boolean;
  • Optional parameters are marked with a question mark: function greet(name?: string) { ... }

βœ… Organizing Your Project

  • Use a clear folder structure (e.g., src/, dist/, types/).
  • Keep related files together in subfolders.
  • Create separate files for different logical components.

❌ Common Mistakes to Avoid

  • Don't ignore TypeScript errors. They're there to help!
  • Avoid mixing type annotations with loose JavaScript.
  • Don't skip creating a tsconfig.json file for larger projects.

Quiz

Question 1 of 14

What does Β§TypeScriptΒ§ add to JavaScript?

  • Static typing
  • Dynamic typing
  • Faster performance
  • New syntax