Mastering TypeScript: Unveiling the Basics of Variables, Functions, and Types

Now that we have a fundamental understanding of TypeScript, let’s explore some of the basics that form the foundation of this powerful language.

1. Variables and Data Types:

In TypeScript, variables can be explicitly typed, allowing for better code clarity and error checking. Here are some examples:

// Explicitly specifying variable types
let userName: string = "John";
let age: number = 30;
let isStudent: boolean = false;

// TypeScript can infer types if not explicitly specified
let city = "New York"; // TypeScript infers the type as string
let temperature = 25.5; // TypeScript infers the type as number

2. Functions and Parameters:

Functions in TypeScript can also have explicit parameter and return types. This is especially useful when writing reusable code or when working in a team.

// Function with explicit parameter and return types
function addNumbers(num1: number, num2: number): number {
  return num1 + num2;
}

const result: number = addNumbers(5, 10);
console.log(result); // Output: 15

3. Interfaces and Type Aliases:

Interfaces and type aliases allow you to define custom types, making your code more expressive and self-documenting.

// Interface for a simple user object
interface User {
  id: number;
  name: string;
  age: number;
}

// Type alias for a complex object type
type Point = {
  x: number;
  y: number;
};

const user: User = { id: 1, name: "Alice", age: 25 };
const coordinates: Point = { x: 10, y: 20 };

These are just the basics, and TypeScript has much more to offer. As we progress through this series, we’ll dive into more advanced topics, such as union and intersection types, generics, and conditional types.

In the next part, we’ll explore these advanced types and show you how they can significantly enhance your TypeScript development experience. Stay tuned for a deeper dive into the world of TypeScript!

Leave a comment

Blog at WordPress.com.

Design a site like this with WordPress.com
Get started