🔥 0
0
Lesson 2 of 10 20 min +100 XP

Basic Types

Every value in TypeScript has a type. Let's explore them through our e-commerce examples.

Primitive Types

string

For text data like product names, descriptions, and customer emails.

let productName: string = "Nike Air Max";
let description: string = "Comfortable running shoes";
let customerEmail: string = "john@example.com";

// Template literals work too
let greeting: string = `Welcome back, ${customerEmail}!`;

number

For prices, quantities, and ratings. TypeScript doesn't distinguish between integers and decimals.

let price: number = 129.99;
let quantity: number = 3;
let rating: number = 4.5;
let stockCount: number = 50;

// Math operations
let subtotal: number = price * quantity;  // 389.97

boolean

For true/false values like stock status and feature flags.

let inStock: boolean = true;
let isOnSale: boolean = false;
let isPremiumMember: boolean = true;
let freeShipping: boolean = subtotal > 100;

---

Type Inference

TypeScript is smart. If you assign a value immediately, it infers the type:

// Explicit types (you write them)
let productId: string = "SKU-12345";
let price: number = 49.99;

// Inferred types (TypeScript figures it out)
let productId = "SKU-12345";  // TypeScript knows: string
let price = 49.99;            // TypeScript knows: number
let inStock = true;           // TypeScript knows: boolean
Best Practice: Let TypeScript infer when it's obvious. Add explicit types for function parameters and when the type isn't clear.

---

Arrays

Arrays hold multiple values of the same type.

// Array of product names
let categories: string[] = ["Electronics", "Clothing", "Home"];

// Array of prices
let recentPrices: number[] = [29.99, 49.99, 19.99, 99.99];

// Array of stock statuses
let availability: boolean[] = [true, true, false, true];

// Alternative syntax (same thing)
let productIds: Array<string> = ["SKU-001", "SKU-002", "SKU-003"];

Working with Arrays

let cartPrices: number[] = [29.99, 49.99, 19.99];

// Add an item
cartPrices.push(9.99);

// Get total
let total = cartPrices.reduce((sum, price) => sum + price, 0);

// Filter expensive items
let expensive = cartPrices.filter(price => price > 20);

---

Tuples

Tuples are fixed-length arrays where each position has a specific type. Great for returning multiple related values.

// [productId, quantity, price]
let cartItem: [string, number, number] = ["SKU-12345", 2, 29.99];

// Access by index
let id = cartItem[0];        // string
let qty = cartItem[1];       // number
let unitPrice = cartItem[2]; // number

// Product with name and price
let product: [string, number] = ["Wireless Mouse", 24.99];

// Coordinate for store location
let storeLocation: [number, number] = [37.7749, -122.4194];

---

null and undefined

These represent "no value" - important for e-commerce edge cases.

// undefined: variable declared but not assigned
let couponCode: string | undefined;  // Customer might not have a coupon

// null: intentionally empty
let selectedProduct: string | null = null;  // Nothing selected yet

// Practical example
let discountCode: string | null = null;

if (isPremiumMember) {
  discountCode = "PREMIUM20";
}

---

The any Type (Use Sparingly!)

any disables type checking. Avoid it when possible.
// ❌ Bad - loses all type safety
let product: any = { name: "Phone", price: 999 };
product = "oops, now I'm a string";  // No error!

// ✅ Better - we'll learn proper typing next lesson
let product = { name: "Phone", price: 999 };

---

Type Challenges

Challenge 1: Fix the Types

// This code has type errors. Can you spot them?
let productName: number = "Laptop";           // ❌
let price: string = 999;                       // ❌
let inStock: number = true;                    // ❌
let tags: string = ["electronics", "sale"];    // ❌
Solution
let productName: string = "Laptop";            // ✅
let price: number = 999;                        // ✅
let inStock: boolean = true;                    // ✅
let tags: string[] = ["electronics", "sale"];   // ✅

Challenge 2: Type the Cart

// Add types to these variables
let itemName = "Bluetooth Speaker";
let unitPrice = 39.99;
let quantity = 2;
let isGiftWrapped = false;
let total = unitPrice * quantity;
Solution
// TypeScript infers these correctly, but explicit types:
let itemName: string = "Bluetooth Speaker";
let unitPrice: number = 39.99;
let quantity: number = 2;
let isGiftWrapped: boolean = false;
let total: number = unitPrice * quantity;

---

Key Takeaways

TypeUse ForExample
stringTextProduct names, emails
numberNumbersPrices, quantities
booleanTrue/falseStock status, flags
type[]ArraysList of products
[T, U]TuplesFixed pairs/triples
nullNo value (intentional)No coupon applied
undefinedNot yet setUnselected option

Next up: Interfaces - defining the shape of complex objects like Products and Orders!