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
To check the installation:
tsc --version
You can also create a tsconfig.json
file to configure TypeScript settings:
tsc --init
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
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];
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
You can also assign custom values to enums:
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
let favoriteColor: Color = Color.Green;
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
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"
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
};
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
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"
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
Intersection Type:
interface Person {
name: string;
}
interface Contact {
phone: string;
}
type PersonWithContact = Person & Contact;
const contact: PersonWithContact = {
name: "Alice",
phone: "123-456-7890"
};
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 };
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;
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;
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 };
- Conditional Types: These types change based on a condition.
type IsString<T> = T extends string ? "Yes" : "No";
type Test = IsString<string>; // "Yes"
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)
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
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.
nice @juniourrau
This is called actual teaching. @jagroop2001 you are doing a lot for DEV community. I really love your content from the very first day.
Thanks @paxnw !!
Your post is awesome π₯. Congrats.
Thanks @martygo
It explains very simply.
Thanks for this post @jagroop2001
Your welcome @siva678 !!
mike.works/course/typescript-funda...
Just amazing, it was a quick refresh for me
Thanks @wizard798
Nice!
Thanks @2pr-io