Lab 03: Advanced Interfaces & Types

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

Interface vs type alias, declaration merging, index signatures, mapped types, conditional types, and the infer keyword.


Step 1: Setup

docker run -it --rm node:20-alpine sh
npm install -g typescript ts-node
mkdir /lab03 && cd /lab03
cat > tsconfig.json << 'EOF'
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true
  }
}
EOF

Step 2: Interface vs Type Alias


Step 3: Declaration Merging

💡 Type aliases cannot merge — declaring type X = ... twice is an error. Interfaces can.


Step 4: Index Signatures


Step 5: Mapped Types


Step 6: Conditional Types


Step 7: The infer Keyword


Step 8: Capstone — Type Utilities Library

Run:

📸 Verified Output:


Summary

Concept
Syntax
Key Difference

Interface

interface X {}

Mergeable, extends

Type alias

type X = {}

Unions, intersections, aliases

Declaration merging

Two interface X

Interfaces only

Index signature

[key: string]: T

Dynamic properties

Mapped type

[K in keyof T]: ...

Transform every property

Conditional type

T extends U ? X : Y

Type-level if/else

infer

T extends F<infer R>

Capture inner type

Last updated