What is TS2532?
TS2532 occurs when you try to access a property or method on a value that TypeScript knows could be undefined. This is similar to TS2531 (possibly null) but specifically for undefined values.
// Example of TS2532 error const users = [{ name: 'John' }, { name: 'Jane' }]; const user = users.find(u => u.name === 'Bob'); console.log(user.name); // Error: Object is possibly 'undefined'
Common Causes
1. Array.find() Method
const items = [1, 2, 3, 4, 5]; const found = items.find(x => x > 10); // found is number | undefined console.log(found.toFixed(2)); // Error!
2. Optional Object Properties
interface User { name: string; email?: string; // Optional property } const user: User = { name: 'John' }; console.log(user.email.toLowerCase()); // Error!
3. Array Index Access
const arr = ['a', 'b', 'c']; const item = arr[10]; // string | undefined console.log(item.toUpperCase()); // Error!
4. Map.get() Method
const map = new Map<string, number>(); map.set('a', 1); const value = map.get('b'); // number | undefined console.log(value.toFixed(2)); // Error!
Solutions
1. If Statement Check
const user = users.find(u => u.name === 'Bob'); // โ Check before using if (user !== undefined) { console.log(user.name); } // โ Truthy check also works if (user) { console.log(user.name); }
2. Optional Chaining (?.)
const user = users.find(u => u.name === 'Bob'); // โ Safe access - returns undefined if user is undefined console.log(user?.name); // โ Works with methods too console.log(user?.name?.toUpperCase());
3. Default Values with ??
const user = users.find(u => u.name === 'Bob'); // โ Provide default value const name = user?.name ?? 'Unknown'; console.log(name); // 'Unknown' if user is undefined
4. Default Parameter Values
interface Config { timeout?: number; retries?: number; } function fetchData(config: Config = {}) { const timeout = config.timeout ?? 5000; const retries = config.retries ?? 3; // Now both are definitely numbers }
5. Non-null Assertion (Use Carefully)
// โ Only when you're certain the value exists const users = [{ name: 'John' }]; const firstUser = users[0]!; // Assert it's not undefined console.log(firstUser.name);
โ ๏ธ Warning
The non-null assertion (!) bypasses TypeScript's safety checks. Only use it when you're absolutely certain the value exists.
Real-World Examples
Working with Arrays
const products = [ { id: 1, name: 'Laptop', price: 999 }, { id: 2, name: 'Phone', price: 699 } ]; // โ find() might return undefined const product = products.find(p => p.id === 3); console.log(product.name); // Error! // โ Handle the undefined case const product = products.find(p => p.id === 3); if (product) { console.log(product.name); } else { console.log('Product not found'); }
React Component Props
interface Props { title: string; subtitle?: string; // Optional } function Header({ title, subtitle }: Props) { return ( <header> <h1>{title}</h1> {subtitle && <h2>{subtitle}</h2>} </header> ); }
API Response Handling
interface ApiResponse<T> { data?: T; error?: string; } async function getUser(id: number): Promise<string> { const response: ApiResponse<User> = await fetch(`/api/users/${id}`); // โ Handle both cases if (response.data) { return response.data.name; } throw new Error(response.error ?? 'Unknown error'); }
๐ก Pro Tip
When using arrays, consider using arr.at(index) instead of arr[index] in TypeScript 5.0+. The .at() method has better type inference for the undefined case.
Summary
- TS2532 protects you from undefined reference errors
- Array methods like
find()andget()can return undefined - Optional properties (?) are undefined when not provided
- Use optional chaining (?.) for safe property access
- Use nullish coalescing (??) for default values
- Always handle the undefined case explicitly