Lab 01: Type System Deep Dive

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

Master TypeScript's type system: union/intersection types, type narrowing, literal types, template literal types, and const assertions.


Step 1: Setup Environment

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

💡 We use module: "commonjs" so ts-node works without ESM configuration.


Step 2: Union and Intersection Types

💡 A | B = either A or B. A & B = both A and B combined.


Step 3: Type Narrowing — typeof / instanceof / in

💡 TypeScript narrows the type inside each if block based on the guard used.


Step 4: Discriminated Union Pattern

💡 The never default branch catches missing cases at compile time — add a new shape and TypeScript errors if you forget to handle it.


Step 5: Literal Types


Step 6: Template Literal Types


Step 7: Const Assertions

💡 as const is invaluable for configuration objects, route maps, and anywhere you need TypeScript to infer the narrowest possible types.


Step 8: Capstone — Full Type Safety Demo

Run it:

📸 Verified Output:


Summary

Concept
Syntax
Use Case

Union type

A | B

Value can be one of several types

Intersection type

A & B

Value must satisfy all types

typeof narrowing

typeof x === 'string'

Primitives

instanceof narrowing

x instanceof Cls

Classes

in narrowing

'prop' in x

Object shapes

Discriminated union

switch(x.kind)

Tagged union pattern

Template literal type

`on${Capitalize<T>}`

String construction types

Const assertion

x as const

Narrow to literal types

Last updated