JS Built-ins
TypeScriptbeginner

Type Guard β€” safe access

πŸ“– Usage Example
function safeGet<T>(obj: T | null | undefined, key: keyof NonNullable<T>) {
  return obj?.[key as keyof typeof obj]
}
// Returns undefined safely when obj is null or undefined

Optional chaining (?.) safely accesses properties on potentially nullish values without throwing.

Type Guards: Safe Property Access

Challenge: Implement safeGet<T, K extends keyof T>(obj: T | null | undefined, key: K): T[K] | undefined β€” returning the property value if obj exists, or undefined otherwise.

safeGet({ name: 'Alice' }, 'name')  // β†’ 'Alice'
safeGet(null, 'name')               // β†’ undefined
πŸ’‘ Hints (1)
  • β€’ obj != null is true when obj is neither null nor undefined (loose inequality).