</>
Skip to content
TypeScript lessons (5/31)

TypeScript — Types

Primitive types

// String
let name: string = "Alice";

// Number (int and float)
let age: number = 30;
let pi: number = 3.14;

// Boolean
let active: boolean = true;

// Null and undefined
let nothing: null = null;
let notSet: undefined = undefined;

// BigInt
let big: bigint = 100n;

// Symbol
let sym: symbol = Symbol("key");

Union types

A value can be one of several types:

// String or number
let id: string | number;
id = "abc";
id = 123;

// Function with union parameter
function format(value: string | number): string {
    if (typeof value === "string") {
        return value.toUpperCase();
    }
    return value.toFixed(2);
}

console.log(format("hello"));  // HELLO
console.log(format(3.14159));  // 3.14

Type narrowing

TypeScript narrows types based on control flow:

function process(value: string | number | boolean) {
    // typeof narrowing
    if (typeof value === "string") {
        return value.toUpperCase();
    }

    if (typeof value === "number") {
        return value.toFixed(2);
    }

    // value is boolean here
    return value ? "yes" : "no";
}

// instanceof narrowing
function formatDate(value: string | Date): string {
    if (value instanceof Date) {
        return value.toLocaleDateString();
    }
    return value;
}

Literal types

// String literal
type Direction = "up" | "down" | "left" | "right";
let dir: Direction = "up";
// dir = "forward"; // Error

// Number literal
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DiceRoll = 3;

// Boolean literal
type Success = { success: true; data: string };
type Failure = { success: false; error: string };
type Result = Success | Failure;

Tuple types

// Fixed-length arrays with specific types
let pair: [string, number] = ["Alice", 30];
// pair = [30, "Alice"]; // Error: wrong types

// Optional elements
let triple: [string, number, boolean?] = ["Alice", 30];
triple = ["Bob", 25, true]; // Also valid

// Rest elements
let rest: [number, ...string[]] = [1, "a", "b", "c"];

// Named tuple (documentation only)
type User = [name: string, age: number, email: string];

Enums

// Numeric enum
enum Status {
    Active,    // 0
    Inactive,  // 1
    Banned     // 2
}

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

// Const enum (inlined at compile time)
const enum Direction {
    Up = "UP",
    Down = "DOWN"
}

let s: Status = Status.Active;
let c: Color = Color.Red;

Intersection types

Combine multiple types:

type HasName = { name: string };
type HasAge = { age: number };
type Person = HasName & HasAge;

const person: Person = {
    name: "Alice",
    age: 30
};

// Interface intersection
interface Printable { print(): void; }
interface Loggable { log(): void; }
type Logger = Printable & Loggable;

Type aliases

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

// Mapped type
type Readonly<T> = { readonly [K in keyof T]: T[K] };

// Conditional type
type IsString<T> = T extends string ? true : false;

typeof and keyof

const obj = { name: "Alice", age: 30 };

// typeof: get the type of a value
type ObjType = typeof obj;
// { name: string; age: number }

// keyof: get the keys of a type
type ObjKeys = keyof ObjType;
// "name" | "age"

// Lookup type
type NameType = ObjType["name"]; // string

Assertion functions

function assertIsString(value: unknown): asserts value is string {
    if (typeof value !== "string") {
        throw new Error("Expected string");
    }
}

function process(input: unknown) {
    assertIsString(input);
    // input is now string
    console.log(input.toUpperCase());
}

Mini Practice

Write TypeScript code that:

  1. Creates a union type for a coin flip ("heads" | "tails")
  2. Uses type narrowing with typeof
  3. Creates an intersection type from two interfaces
  4. Uses keyof to create a type-safe property accessor

Up Next

In the next lesson, you'll learn about Variables — declarations, scoping, and const assertions.

Related Topics

Frequently Asked Questions about Types

What is Types in TypeScript?

Types is a fundamental concept in TypeScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Types?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Types.

Why is Types important in TypeScript?

Types is essential for TypeScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.