Lab 11: TypeScript Advanced
Overview
Step 1: Setup
cd /tmp && npm init -y --quiet
npm install typescript --save-dev
npx tsc --versionStep 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 | booleanStep 3: Mapped Types
Step 4: Template Literal Types
Step 5: The infer Keyword
infer KeywordStep 6: Utility Types Deep Dive
Step 7: Declaration Merging & Module Augmentation
Step 8: Capstone — TypeScript Compile Demo
Summary
Feature
Syntax
Use Case
Last updated
