Lab 14: TypeScript Basics in JS

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

Overview

Use TypeScript features within JavaScript: JSDoc type annotations, @ts-check, optional chaining (?.), nullish coalescing (??), logical assignment operators (&&=/||=/??=), and the modern safety operators.


Step 1: Optional Chaining (?.)

// Without optional chaining — verbose null checks
function getCity_old(user) {
  return user && user.address && user.address.city;
}

// With optional chaining — clean and safe
function getCity(user) {
  return user?.address?.city;
}

const users = [
  { name: 'Alice', address: { city: 'New York', zip: '10001' } },
  { name: 'Bob', address: null },
  { name: 'Charlie' } // No address property
];

users.forEach(u => {
  console.log(u.name, '->', getCity(u) ?? '(no city)');
});
// Alice -> New York
// Bob -> (no city)
// Charlie -> (no city)

// Optional chaining with method calls
const config = {
  getTheme: () => 'dark',
  // getLocale is missing
};
console.log(config.getTheme?.());  // 'dark'
console.log(config.getLocale?.());  // undefined (no error!)

// Optional chaining with arrays
const data = { items: [1, 2, 3] };
const empty = {};
console.log(data.items?.[0]); // 1
console.log(empty.items?.[0]); // undefined (not a TypeError!)

💡 ?. short-circuits: if the left side is null or undefined, the whole expression returns undefined without evaluating the rest.


Step 2: Nullish Coalescing (??)


Step 3: Logical Assignment Operators


Step 4: JSDoc Type Annotations


Step 5: Modern JavaScript Type Safety


Step 6: Practical Modern Patterns


Step 7: Error Handling with Modern Syntax


Step 8: Capstone — Type-Safe Utilities

Run verification:

📸 Verified Output:


Summary

Feature
Syntax
Behavior

Optional chaining

obj?.prop

Returns undefined if obj is null/undefined

Optional method call

obj?.method()

Calls only if method exists

Optional index

arr?.[i]

Indexes only if arr is defined

Nullish coalescing

a ?? b

Returns b only if a is null/undefined

Logical AND assign

a &&= b

Assigns b only if a is truthy

Logical OR assign

a ||= b

Assigns b only if a is falsy

Nullish assign

a ??= b

Assigns b only if a is null/undefined

JSDoc @type

/** @type {string} */

Editor/TypeScript hints

@ts-check

File comment

Enable TS checking in .js

Last updated