DEV Community

Cover image for Learn TypeScript from A to Z πŸš€
Jagroop Singh
Jagroop Singh

Posted on

Learn TypeScript from A to Z πŸš€

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!

Top comments (14)

Collapse
 
pengeszikra profile image
Peter Vivo

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

Collapse
 
juniourrau profile image
Ravin Rau

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.

Collapse
 
jagroop2001 profile image
Jagroop Singh
Collapse
 
paxnw profile image
caga

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

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @paxnw !!

Collapse
 
martygo profile image
Martins Gouveia

Your post is awesome πŸ”₯. Congrats.

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @martygo

Collapse
 
siva678 profile image
Sivasankaran

It explains very simply.
Thanks for this post @jagroop2001

Collapse
 
jagroop2001 profile image
Jagroop Singh

Your welcome @siva678 !!

Collapse
 
eshimischi profile image
eshimischi
Collapse
 
wizard798 profile image
Wizard

Just amazing, it was a quick refresh for me

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @wizard798

Collapse
 
2pr-io profile image
2PR

Nice!

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @2pr-io