TS2532

Object is possibly 'undefined'

๐Ÿ“š Difficulty: Beginner โฑ๏ธ 5 min read ๐Ÿ”„ Updated: Feb 2025

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

Still Confused by Your Error?

Paste your TypeScript error into our analyzer for instant, detailed explanations.

Try Error Analyzer โ†’