Lab 14: TypeScript Basics in JS
Overview
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!)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
Summary
Feature
Syntax
Behavior
Last updated
