Skip to main content

Module 2: Basic Types

TypeScript provides a rich set of built-in types that extend JavaScript. This module covers all fundamental types you'll use daily.


1. Primitive Types

String

let fullName: string = "John Doe";
let greeting: string = `Hello, ${fullName}`;
let multiLine: string = `
This is a
multi-line string
`;

Number

let age: number = 25;
let price: number = 99.99;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

Boolean

let isActive: boolean = true;
let hasPermission: boolean = false;
let isValid: boolean = age > 18;
Type Inference

TypeScript can often infer types automatically:

let name = "Alice"; // TypeScript infers string

2. Array Types

Method 1: Type[]

let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
let flags: boolean[] = [true, false, true];

Method 2: Array<Type>

let scores: Array<number> = [90, 85, 95];
let tags: Array<string> = ["typescript", "javascript"];
Best Practice

Prefer Type[] syntax for simple arrays. Use Array<Type> for complex generic types.


3. Tuple Types

Tuples are fixed-length arrays with known types for each position.

// Define a tuple
let person: [string, number];
person = ["Alice", 25]; // ✅ Correct

person = [25, "Alice"]; // ❌ Error: Type mismatch

// Accessing tuple elements
let name: string = person[0];
let age: number = person[1];

// Destructuring tuples
let [userName, userAge] = person;

Tuple with Optional Elements

let point: [number, number, number?] = [10, 20];
point = [10, 20, 30]; // Also valid

Tuple with Rest Elements

let data: [string, ...number[]] = ["scores", 90, 85, 95];

4. Enum Types

Enums define a set of named constants.

Numeric Enums

enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}

let move: Direction = Direction.Up;
console.log(move); // Output: 0

Enums with Custom Values

enum Status {
Active = 1,
Inactive = 0,
Pending = 2
}

let userStatus: Status = Status.Active;

String Enums

enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}

let favoriteColor: Color = Color.Red;
console.log(favoriteColor); // Output: "RED"

Const Enums (Performance Optimization)

const enum HttpStatus {
OK = 200,
NotFound = 404,
ServerError = 500
}

let status: HttpStatus = HttpStatus.OK;
// Compiled: let status = 200 (no enum object created)

5. Any Type

The any type disables type checking.

let variable: any = "Hello";
variable = 42; // ✅ OK
variable = true; // ✅ OK
variable.toFixed(); // ✅ No error (even if wrong)
Avoid Any

Use any sparingly! It defeats the purpose of TypeScript.

When to Use Any

  • Working with dynamic content (user input, APIs)
  • Migrating JavaScript to TypeScript gradually
  • Truly unknown data structures

6. Unknown Type

unknown is a type-safe alternative to any.

let value: unknown = "Hello";

// ❌ Cannot use directly
// value.toUpperCase(); // Error

// ✅ Must check type first
if (typeof value === "string") {
value.toUpperCase(); // OK
}

Unknown vs Any

TypeType SafetyUsage
anyNoneDisables type checking
unknownFullRequires type checking before use
Best Practice

Prefer unknown over any when the type is truly unknown.


7. Void Type

Used for functions that don't return a value.

function logMessage(message: string): void {
console.log(message);
}

function processData(): void {
// Do something but don't return
}
Void vs Undefined

void is for function return types. Variables of type void can only be undefined or null.


8. Null and Undefined

let nothing: null = null;
let notDefined: undefined = undefined;

// With strictNullChecks enabled
let name: string = null; // ❌ Error
let age: number = undefined; // ❌ Error

// Allow null/undefined explicitly
let nullable: string | null = null; // ✅ OK

9. Never Type

Represents values that never occur.

Use Case 1: Functions That Never Return

function throwError(message: string): never {
throw new Error(message);
}

function infiniteLoop(): never {
while (true) {
// Never returns
}
}

Use Case 2: Exhaustive Type Checking

type Shape = "circle" | "square";

function getArea(shape: Shape): number {
switch (shape) {
case "circle":
return Math.PI * 10 * 10;
case "square":
return 10 * 10;
default:
const _exhaustive: never = shape;
return _exhaustive;
}
}

10. Object Type

let user: object = {
name: "Alice",
age: 25
};

// Better: Use specific object structure
let employee: { name: string; age: number; } = {
name: "Bob",
age: 30
};

11. Type Assertion (Type Casting)

Tell TypeScript to treat a value as a specific type.

Method 1: Angle Bracket Syntax

let value: any = "Hello TypeScript";
let length: number = (<string>value).length;

Method 2: as Syntax (Preferred in JSX)

let value: any = "Hello TypeScript";
let length: number = (value as string).length;
Type Assertion Caution

Type assertion doesn't perform runtime checks. You're telling TypeScript "trust me, I know what I'm doing."


12. Literal Types

Specify exact values a variable can hold.

String Literals

let direction: "up" | "down" | "left" | "right";
direction = "up"; // ✅ OK
direction = "north"; // ❌ Error

Numeric Literals

let diceRoll: 1 | 2 | 3 | 4 | 5 | 6;
diceRoll = 4; // ✅ OK
diceRoll = 7; // ❌ Error

Boolean Literals

let isTrue: true = true;
let isFalse: false = false;

13. Type Aliases

Create reusable type definitions.

type StringOrNumber = string | number;
type Point = { x: number; y: number; };
type Callback = (data: string) => void;

let value: StringOrNumber = "Hello";
let point: Point = { x: 10, y: 20 };
let handler: Callback = (data) => console.log(data);

Key Takeaways

✅ TypeScript has rich type system beyond JavaScript
✅ Use specific types instead of any
Tuples for fixed-length, mixed-type arrays
Enums for named constants
Literal types for exact values
Type assertions when you know better than TypeScript


Practice Exercises

Exercise 1: Type Annotations

Create variables with explicit types for your personal information.

let firstName: string = "Your Name";
let age: number = 25;
let isStudent: boolean = true;

Exercise 2: Arrays and Tuples

let scores: number[] = [90, 85, 95];
let user: [string, number, boolean] = ["Alice", 25, true];

Exercise 3: Enums

Create an enum for days of the week and use it.

enum DayOfWeek {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

let today: DayOfWeek = DayOfWeek.Monday;

Next Steps

In Module 3, we'll explore Functions in TypeScript including parameter types, return types, optional parameters, and function overloading.