TypeScript Basics

Core Concepts & Fundamental Syntax

Basic Types

Primitive Types
The building blocks of TypeScript
.ts
// String
let name: string = "John"

// Number
let age: number = 25

// Boolean
let isActive: boolean = true

// Null and Undefined
let data: null = null
let value: undefined = undefined

Type Inference

TypeScript is Smart
It can often figure out types automatically
.ts
// TypeScript infers these types
let message = "Hello" // string
let count = 42 // number
let items = [1, 2, 3] // number[]

// Function return type inferred
function double(x: number) {
return x * 2 // returns number
}
When to Be Explicit
Sometimes you need to specify types
.ts
// When inference isn't enough
let data: any = JSON.parse('name": "John')
let user: Person = data

// Function parameters always need types
function process(callback: (result: string) => void) {
// ...
}

Union Types

Multiple Possible Types
When a value can be one of several types
.ts
// Union types with |
let id: string | number
id = "abc123" // ✅ Valid
id = 456 // ✅ Valid

// Type narrowing with typeof
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase()) // TypeScript knows it's a string
} else {
console.log(id.toFixed(2)) // TypeScript knows it's a number
}

Pro Tip: TypeScript"s control flow analysis automatically narrows union types based on your conditional checks!

Type Aliases vs Interfaces

Type Aliases
Creating reusable type definitions
.ts
// Type alias
type Status = "loading" | "success" | "error"

type User = {
id: number
name: string
status: Status
}

// Union of types
type Shape = Circle | Rectangle
Interfaces
Defining object contracts
.ts
// Interface
interface User {
id: number
name: string
}

// Interface extension
interface AdminUser extends User {
permissions: string[]
}

// Interface merging
interface User {
email: string
}