Generic interfaces & type aliases
Define generic interfaces and type aliases; add constraints, defaults, and understand where each shines.
Generic interfaces & type aliases is a free TypeScript Academy lesson on CoddyKit — 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, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Lesson overview
Goal: Apply structured concurrency with coroutineScope, understand exception propagation, and use cancellation tools safely.
Intro
Goal: Create reusable shapes using generic interfaces and type aliases. You will add constraints, defaults, and learn key differences.
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.
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")
}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);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")
}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));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")
}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: readonlywithTimeout 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")
}
}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)Interfaces vs types check
Quick check: Which statement about generic interfaces vs type aliases is TRUE?
Structured concurrency failure rule
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.
Recap
Recap: Use generic interfaces and type aliases to model reusable shapes. Add constraints, defaults, and remember: only interfaces merge.
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, and the TypeScript Academy course includes 3 lessons in total. 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.
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; this is — lesson 1 of 3, so you can start here or from the beginning and move at your own pace.
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
- Generic interfaces & type aliases
- Conditional Types (intro) & distribution over unions
- Reusable patterns for data models