TypeScript Lesson 3: Basic Types

📘 TypeScript CourseLesson 3 of 12 · 25% complete

Types are the foundation of TypeScript. These are the types you’ll use in 90% of your code.

Primitive Types

// string, number, boolean
const name: string = "Alice";
const age: number = 30;
const active: boolean = true;

// number covers int AND float
const price: number = 9.99;
const count: number = 42;

// Type inference — TypeScript figures it out
const language = "TypeScript";  // inferred as string
const year = 2024;             // inferred as number
// (you don't always need to write the type!)

Arrays and Tuples

// Arrays
const names: string[] = ["Alice", "Bob", "Charlie"];
const scores: number[] = [98, 87, 92];

// Generic array syntax (same thing)
const items: Array<string> = ["a", "b", "c"];

// Tuple: fixed length, fixed types at each position
const point: [number, number] = [10, 20];
const entry: [string, number] = ["age", 30];

Special Types

// any — escape hatch (avoid when possible)
let data: any = "hello";
data = 42;          // allowed
data = { x: 1 };   // allowed (loses type safety!)

// unknown — safer alternative to any
let input: unknown = JSON.parse(someText);
if (typeof input === "string") {
  input.toUpperCase();  // OK, narrowed to string
}

// void — function returns nothing
function log(msg: string): void {
  console.log(msg);
}

// null and undefined
let value: string | null = null;   // can be string or null
let opt: string | undefined;       // might not be set

🏋️ Practice Task

Type all of these: an array of 5 product names (strings), a 2D point tuple [x, y], a function that takes a string and returns its length (number), a nullable string that starts as null then gets assigned “hello”.

💡 Hint: const point: [number, number] = [10, 20]. For null: let text: string | null = null; text = “hello”;

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *