TypeScript is a superset of JavaScript that adds static types to the language. It helps you catch errors early during development, improves code readability, and provides better autocompletion. This guide will introduce you to the core concepts of TypeScript.
Why Use TypeScript?
- Static Typing: Catch type-related errors at compile time, not runtime.
- Code Completion: Your editor can provide better suggestions and autocompletion.
- Readability: Explicit types make code easier to understand and maintain.
Basic Types
TypeScript has several basic types:
let isLoggedIn: boolean = true;
let userAge: number = 30;
let userName: string = "Alice";
let hobbies: string[] = ["reading", "coding"];
let user: [number, string] = [1, "Alice"]; // Tuple
Interfaces
Interfaces define the shape of an object. They are a powerful way to enforce a contract for your objects.
interface User {
id: number;
name: string;
email?: string; // Optional property
}
function greetUser(user: User) {
console.log(`Hello, ${user.name}`);
}
const myUser: User = { id: 1, name: "Bob" };
greetUser(myUser);
Comments
Post a Comment