TypeScript Academy · Lesson

Generic interfaces & type aliases

Define generic interfaces and type aliases; add constraints, defaults, and understand where each shines.

Lesson 1 of 316 steps

Generic interfaces & type aliases is a free TypeScript Academy lesson on CoddyKit. This is lesson 1 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, and your progress syncs across the web and the CoddyKit app. The TypeScript Academy course includes 3 lessons in total.

Intro

Goal: Create reusable shapes using generic interfaces and type aliases. You will add constraints, defaults, and learn key differences.

Lesson overview

Goal: Apply structured concurrency with coroutineScope, understand exception propagation, and use cancellation tools safely.

Generic interface

A generic interface holds a type parameter. Callers substitute concrete types (e.g., Box<number>).

interface Box<T> {
  value: T;
}

const nBox: Box<number> = { value: 42 };
const sBox: Box<string> = { value: "ts" };
console.log(nBox.value, sBox.value);

Key ideas

  • coroutineScope waits for all children; failure cancels siblings.
  • launch fails immediately in the scope; async surfaces errors on await().
  • withTimeout cancels work after a limit.
  • Wrap scopes with try/catch to handle exceptions.

Generic type alias

A type alias can also be generic and express objects, functions, unions, or intersections.

type Pair<A, B> = { first: A; second: B };

const p1: Pair<number, string> = { first: 1, second: "one" };
const p2: Pair<boolean, boolean> = { first: true, second: false };
console.log(p1, p2);

Scope waiting behavior

coroutineScope creates a child scope that completes only after its children finish.

import kotlinx.coroutines.*

suspend fun doTwoTasks(): Unit = coroutineScope {
    // Both run concurrently and the scope waits for them
    launch { delay(150); println("Task A done") }
    launch { delay(100); println("Task B done") }
    // returning Unit implicitly after children complete
}

fun main() = runBlocking {
    doTwoTasks()
    println("Scope completed")
}

Constraints

Add an extends constraint so T exposes required members (e.g., id) to the interface methods.

interface Repository<T extends { id: number }> {
  getById(id: number): T | undefined;
  save(entity: T): void;
}

type User = { id: number; name: string };

const memRepo: Repository<User> = {
  store: [] as User[],
  getById(id) {
    return this.store.find(u => u.id === id);
  },
  save(u) {
    this.store.push(u);
  }
} as unknown as Repository<User>;

memRepo.save({ id: 1, name: "Ada" });
console.log(memRepo.getById(1));

Failure cancels siblings

If one child throws, the scope cancels siblings and rethrows to the caller; use try/catch at the call site.

import kotlinx.coroutines.*

suspend fun failingGroup() = coroutineScope {
    val a = launch {
        try {
            repeat(5) { i ->
                println("A $i"); delay(60)
            }
        } finally {
            println("A cancelled")
        }
    }
    launch {
        delay(120)
        throw IllegalStateException("boom") // failure in child
    }
    a.join() // will be cancelled when sibling fails
}

fun main() = runBlocking {
    try {
        failingGroup()
    } catch (e: Exception) {
        println("Caught in caller: ${e.message}")
    }
    println("Caller continues")
}

Defaults & extension

Provide default type parameters for ergonomics and build on types with utilities (e.g., Readonly<Box<T>>).

interface ApiResponse<T = unknown> {
  data: T;
  ok: boolean;
}

type ReadonlyBox<T> = Readonly<Box<T>>;

const r1: ApiResponse = { data: "ok", ok: true };      // T defaults to unknown
const r2: ApiResponse<number> = { data: 200, ok: true };
const rb: ReadonlyBox<string> = { value: "fixed" };
// rb.value = "change"; // Error: readonly

async + await errors

async exceptions are raised when you call await(); handle them with try/catch.

import kotlinx.coroutines.*

suspend fun parseAsync(s: String) = coroutineScope {
    val deferred = async {
        delay(50)
        s.toInt() // may throw NumberFormatException
    }
    try {
        println("Result = ${deferred.await()}") // error appears here
    } catch (e: NumberFormatException) {
        println("Handled parse error: ${e::class.simpleName}")
    }
}

fun main() = runBlocking {
    parseAsync("12")
    parseAsync("xx")
}

Merging differences

Interfaces support declaration merging. Type aliases cannot merge; duplicate names are errors.

interface Settings { theme: string }
interface Settings { lang: string }
// Merged: Settings has { theme: string; lang: string }
const s: Settings = { theme: "dark", lang: "en" };

// type Settings = { foo: string };
// Error: Duplicate identifier 'Settings' for type aliases (no merging)

withTimeout cancellation

Use withTimeout to bound work; it cancels the child and throws TimeoutCancellationException.

import kotlinx.coroutines.*

suspend fun slowOp(): Int {
    delay(300) // pretend work
    return 42
}

fun main() = runBlocking {
    try {
        val result = withTimeout(150) { slowOp() } // cancels after 150ms
        println("Got $result")
    } catch (e: TimeoutCancellationException) {
        println("Timed out and cancelled")
    }
}

Interfaces vs types check

Quick check: Which statement about generic interfaces vs type aliases is TRUE?

Structured concurrency failure rule

In coroutineScope, what happens if one child coroutine fails with an exception?

Recap

Recap: Use generic interfaces and type aliases to model reusable shapes. Add constraints, defaults, and remember: only interfaces merge.

Recap

Recap: Use coroutineScope to group work; a failing child cancels siblings. Handle errors with try/catch, surface async failures on await(), and cancel long tasks with withTimeout.

Free to start

Learn TypeScript with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
101
Lessons
352

Frequently Asked Questions

Is the “Generic interfaces & type aliases” lesson free?

Yes — the full text of “Generic interfaces & type aliases” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO. The TypeScript Academy course includes 3 lessons in total.

What will I learn in “Generic interfaces & type aliases”?

Define generic interfaces and type aliases; add constraints, defaults, and understand where each shines. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 3.

How long does the “Generic interfaces & type aliases” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Generic interfaces & type aliases
  2. Conditional Types (intro) & distribution over unions
  3. Reusable patterns for data models
← Back to TypeScript Academy