Diving into TypeScript: My First Day of Learning!

naymhdev

Naym Hossen

Posted on November 1, 2024

Diving into TypeScript: My First Day of Learning!

Today, I started with TypeScript fundamentals and explored how it makes JavaScript development safer and more powerful. Here’s a breakdown of what I covered and some code examples!

1. Reference Types and Literal Types

Readonly & Optional Properties: These are great for ensuring certain values stay fixed, while optional properties provide flexibility.

type Person = {
  readonly name: string;  // Name cannot be changed
  age: number;
  isMarried?: boolean;  // Optional property
};

const person: Person = { name: "John Doe", age: 30 };
// person.name = "Jane Doe";  // Error: Cannot modify readonly property
Enter fullscreen mode Exit fullscreen mode

2. Typed Functions

Function with Explicit Types: Ensures functions return the correct type, enhancing code predictability.

function sum(num1: number, num2: number): number {
  return num1 + num2;
}

// Arrow Function
const addNum = (add1: number, add2: number): number => add1 + add2;
Enter fullscreen mode Exit fullscreen mode

3. Arrays and Typed Array Methods

Typed Arrays: TypeScript enforces type safety in arrays, making methods like .map() safer.

const array: number[] = [1, 3, 2, 4, 5, 6];
const newArray: number[] = array.map((ele: number): number => ele * ele);
console.log(newArray);  // [1, 9, 4, 16, 25, 36]
Enter fullscreen mode Exit fullscreen mode

4. Spread, Rest, and Destructuring Operators

Spread & Rest Operators make handling dynamic data smooth, while destructuring simplifies assignments.

const [first, ...rest] = array;
console.log(first);  // 1
console.log(rest);   // [3, 2, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

5. Type Aliases and Union Types

Type Aliases: Creating reusable types for better code structure.

Union Types: Allowing variables to hold multiple types, adding flexibility without sacrificing safety.

type ID = string | number;

let userId: ID = 101;  // Could be a string or a number
userId = "A102";
Enter fullscreen mode Exit fullscreen mode

6. Conditional Types and Operators (???|&&)

Using optional chaining (?) and nullish coalescing (??) operators help keep the code clean and avoid unnecessary null checks.

function greet(name?: string) {
  const displayName = name ?? "Guest";
  console.log(`Hello, ${displayName}!`);
}

greet();           // Hello, Guest!
greet("Naym");  // Hello, Naym!
Enter fullscreen mode Exit fullscreen mode

Starting with TypeScript has been an eye-opener in terms of writing clean, type-safe code! Excited to keep building on this foundation. 💪🔥

💖 💪 🙅 🚩
naymhdev
Naym Hossen

Posted on November 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related