Lab 11: TypeScript Advanced

Time: 30 minutes | Level: Advanced | Docker: docker run -it --rm node:20-alpine sh

Overview

Master advanced TypeScript: conditional types, mapped types, template literal types, the infer keyword, utility types, declaration merging, and module augmentation.


Step 1: Setup

cd /tmp && npm init -y --quiet
npm install typescript --save-dev
npx tsc --version

Step 2: Conditional Types

// Conditional types: T extends U ? X : Y
type IsArray<T> = T extends any[] ? true : false;
type IsString<T> = T extends string ? true : false;
type IsFunction<T> = T extends (...args: any[]) => any ? true : false;

type TestArray = IsArray<number[]>;    // true
type TestString = IsArray<string>;     // false
type TestFn = IsFunction<() => void>;  // true

// Distributive conditional types
type NonNullable<T> = T extends null | undefined ? never : T;
type Flatten<T> = T extends (infer U)[] ? U : T;
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;

type FlatNumber = Flatten<number[]>;      // number
type FlatString = Flatten<string>;        // string (not array)
type Unwrapped = UnwrapPromise<Promise<string>>; // string

// Deep flattening
type DeepFlatten<T> = T extends (infer U)[]
  ? DeepFlatten<U>
  : T;

type Nested = DeepFlatten<number[][][]>; // number

// Extract and Exclude
type Strings = Extract<string | number | boolean, string>; // string
type NoStrings = Exclude<string | number | boolean, string>; // number | boolean

Step 3: Mapped Types


Step 4: Template Literal Types


Step 5: The infer Keyword


Step 6: Utility Types Deep Dive


Step 7: Declaration Merging & Module Augmentation


Step 8: Capstone — TypeScript Compile Demo

📸 Verified Output:


Summary

Feature
Syntax
Use Case

Conditional type

T extends U ? X : Y

Type branching

Mapped type

{ [K in keyof T]: ... }

Transform all properties

Template literal

`${A}-${B}`

String type combinations

infer

T extends (infer U)[]

Extract inner types

Partial<T>

Built-in

Make all fields optional

Required<T>

Built-in

Make all fields required

Pick<T, K>

Built-in

Select subset of fields

Omit<T, K>

Built-in

Remove subset of fields

ReturnType<T>

Built-in

Extract function return type

Declaration merging

Repeat interface

Extend existing types

Module augmentation

declare module '...'

Add to third-party types

Last updated