Lesson 8 of 8
Practice & Quiz - Advanced Types
Test your mastery of TypeScript's advanced type system - utility types, keyof/typeof, mapped types, conditional types with infer, and template literal types - with a hands-on exercise and 5 quiz questions.
Practical: Typed API Response Wrapper
// Build a fully-typed API response utility using advanced types
import { z } from "zod";
// ── Branded IDs - zero runtime cost ──────────────────────────
type Brand<T, B extends string> = T & { readonly __brand: B };
type TaskId = Brand<number, "TaskId">;
type UserId = Brand<number, "UserId">;
const taskId = (n: number): TaskId => n as TaskId;
const userId = (n: number): UserId => n as UserId;
// ── ApiResponse - wraps any data shape ───────────────────────
type ApiSuccess<T> = { ok: true; data: T; timestamp: string };
type ApiFailure<E> = { ok: false; error: E; timestamp: string };
type ApiResponse<T, E = string> = ApiSuccess<T> | ApiFailure<E>;
// ── Generic helper that preserves the resolved type ──────────
async function apiCall<T>(
fetcher: () => Promise<T>,
): Promise<ApiResponse<T>> {
try {
const data = await fetcher();
return { ok: true, data, timestamp: new Date().toISOString() };
} catch (e) {
const error = e instanceof Error ? e.message : "Unknown error";
return { ok: false, error, timestamp: new Date().toISOString() };
}
}
// ── Template literal type - typed event channel names ────────
type Domain = "task" | "user" | "project";
type Action = "created" | "updated" | "deleted";
type Channel = `${Domain}:${Action}`; // "task:created" | "user:updated" | ...
// ── Usage - fully inferred ────────────────────────────────────
const result = await apiCall(() => fetch("/api/tasks").then(r => r.json()));
if (result.ok) {
console.log("Data:", result.data); // inferred type ✅
} else {
console.error("Error:", result.error);
}Module Quiz
What does `Omit<Task, 'id' | 'createdAt'>` produce?
Tip
Tip
Practice Practice Quiz Advanced Types in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
TypeScript = JavaScript + static types → fewer bugs, better tooling
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Advanced Types from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Advanced Types is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Finished this lesson?