Learn TypeScript from A to Z 🚀
Jagroop Singh

Jagroop Singh @jagroop2001

About: 👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views

Location:
India
Joined:
Apr 5, 2022

Learn TypeScript from A to Z 🚀

Publish Date: Dec 6 '24
79 18

TypeScript is a powerful tool for JavaScript developers looking to add static typing to their projects. Whether you’re a beginner or an experienced developer, this blog will walk you through TypeScript concepts with examples that’ll stick!


1. What is TypeScript? 🤔

TypeScript is a superset of JavaScript that adds static types. It helps you catch errors early and improves your code's readability. TypeScript compiles down to regular JavaScript, so it works in any environment where JavaScript runs!


2. Setting Up TypeScript 🔧

Start by installing TypeScript globally with npm:

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

To check the installation:

tsc --version
Enter fullscreen mode Exit fullscreen mode

You can also create a tsconfig.json file to configure TypeScript settings:

tsc --init
Enter fullscreen mode Exit fullscreen mode

3. Basic Types 🏷️

In TypeScript, types are the foundation. Let’s start with some basic types:

let name: string = "John Doe"; // A string
let age: number = 25; // A number
let isStudent: boolean = true; // A boolean
Enter fullscreen mode Exit fullscreen mode

4. Arrays and Tuples 📚

Arrays store multiple items, while tuples are arrays with fixed types and lengths.

// Array
let scores: number[] = [90, 85, 78];

// Tuple
let person: [string, number] = ["John", 25];
Enter fullscreen mode Exit fullscreen mode

5. Enums 🎉

Enums are a great way to represent a collection of related values. For example, representing days of the week:

enum Day {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}

let today: Day = Day.Monday;
console.log(today); // Outputs: 1
Enter fullscreen mode Exit fullscreen mode

You can also assign custom values to enums:

enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

let favoriteColor: Color = Color.Green;
Enter fullscreen mode Exit fullscreen mode

6. Functions and Return Types 📝

In TypeScript, you can specify the return type of a function to ensure consistency.

function greet(name: string): string {
  return `Hello, ${name}!`;
}

let message = greet("Alice"); // TypeScript knows this is a string
Enter fullscreen mode Exit fullscreen mode

You can also define functions that accept multiple types:

function combine(a: string | number, b: string | number): string | number {
  return a + b;
}

console.log(combine(5, 10)); // 15
console.log(combine("Hello", "World")); // "HelloWorld"
Enter fullscreen mode Exit fullscreen mode

7. Interfaces 📐

Interfaces define the shape of an object. They allow you to specify required properties and their types:

interface Person {
  name: string;
  age: number;
}

let user: Person = {
  name: "Alice",
  age: 30
};
Enter fullscreen mode Exit fullscreen mode

8. Classes and Objects 💼

TypeScript supports object-oriented programming through classes.

class Car {
  make: string;
  model: string;

  constructor(make: string, model: string) {
    this.make = make;
    this.model = model;
  }

  displayInfo(): string {
    return `Car: ${this.make} ${this.model}`;
  }
}

let myCar = new Car("Toyota", "Corolla");
console.log(myCar.displayInfo()); // Car: Toyota Corolla
Enter fullscreen mode Exit fullscreen mode

9. Generics 🧩

Generics allow you to create reusable components with a flexible type. This is useful when you don’t know the type in advance.

function identity<T>(arg: T): T {
  return arg;
}

let num = identity(123); // 123
let str = identity("Hello"); // "Hello"
Enter fullscreen mode Exit fullscreen mode

10. Union and Intersection Types ⚔️

Union types allow a variable to hold values of different types, while intersection types combine multiple types into one.

Union Type:

function printId(id: string | number) {
  console.log(id);
}

printId(101); // Works fine
printId("abc"); // Works fine
Enter fullscreen mode Exit fullscreen mode

Intersection Type:

interface Person {
  name: string;
}

interface Contact {
  phone: string;
}

type PersonWithContact = Person & Contact;

const contact: PersonWithContact = {
  name: "Alice",
  phone: "123-456-7890"
};
Enter fullscreen mode Exit fullscreen mode

11. Type Aliases 🔠

You can create your own type names using type aliases.

type Point = { x: number; y: number };

let point: Point = { x: 10, y: 20 };
Enter fullscreen mode Exit fullscreen mode

12. Type Assertions 🚀

Sometimes, TypeScript cannot infer the exact type. In such cases, you can assert the type:

let someValue: any = "Hello, TypeScript!";
let strLength: number = (someValue as string).length;
Enter fullscreen mode Exit fullscreen mode

13. TypeScript with React 💻

TypeScript works seamlessly with React! Here’s an example:

import React from 'react';

interface ButtonProps {
  label: string;
}

const Button: React.FC<ButtonProps> = ({ label }) => {
  return <button>{label}</button>;
};

export default Button;
Enter fullscreen mode Exit fullscreen mode

14. Advanced Types 🌐

  • Mapped Types: These allow you to create types based on existing types dynamically.
type PersonKeys = "name" | "age";
type PersonMapped = { [key in PersonKeys]: string };
Enter fullscreen mode Exit fullscreen mode
  • Conditional Types: These types change based on a condition.
type IsString<T> = T extends string ? "Yes" : "No";
type Test = IsString<string>; // "Yes"
Enter fullscreen mode Exit fullscreen mode

Answer this ?? 🤯

So, after all this, here’s a tricky question for you:
If TypeScript is a superset of JavaScript and it compiles down to JavaScript, can you tell me why we need TypeScript at all? Is it just about type safety, or is there something more powerful hiding in the background? What do you think? Drop your thoughts in the comments! 😅


Conclusion

And there you have it, folks! From basic types to advanced features, you’ve just taken a crash course in TypeScript. 🌟 With TypeScript, you’re not just adding types; you’re adding structure, safety, and clarity to your code. Start using it in your projects today and see how it transforms your JavaScript experience!

Comments 18 total

  • Martins Gouveia
    Martins GouveiaDec 6, 2024

    Your post is awesome 🔥. Congrats.

  • caga
    cagaDec 7, 2024

    This is called actual teaching. @jagroop2001 you are doing a lot for DEV community. I really love your content from the very first day.

  • Himanshu Sorathiya
    Himanshu Sorathiya Dec 7, 2024

    Just amazing, it was a quick refresh for me

  • Peter Vivo
    Peter VivoDec 7, 2024

    My short answer is: because TS improving developer life with give power to work with typesafe way.
    Long answer is: don't need to write TS directly, JSDoc still working without using another languages instead of JS. My detailed arguing to JSDoc

  • Ravin Rau
    Ravin RauDec 7, 2024

    Development Experience and Productivity
    Type information makes your IDE much smarter - you get better autocomplete, inline documentation, and can catch errors before you even run the code. Imagine having a co-pilot that constantly checks your work and makes suggestions.

    Safer Refactoring
    When you need to make changes across a large codebase, TypeScript acts as a safety net. Change the shape of an object, and TypeScript will show you every place that needs to be updated. In JavaScript, you'd have to catch these issues at runtime.

    Better Design Patterns
    TypeScript enables more advanced patterns like discriminated unions and generics that are harder to implement safely in JavaScript.

  • 2PR
    2PRDec 9, 2024

    Nice!

  • Sivasankaran
    Sivasankaran Dec 10, 2024

    It explains very simply.
    Thanks for this post @jagroop2001

Add comment