πŸ”§ Error Fixes
Β· 1 min read

TypeScript Strict Mode Errors β€” How to Fix Them


// tsconfig.json
{ "compilerOptions": { "strict": true } }
// Suddenly: 200+ errors

TypeScript strict mode enables several checks at once. Here’s how to fix the most common ones.

Fix 1: Object Is Possibly Undefined

// ❌ strict null checks
const user = users.find(u => u.id === 1);
console.log(user.name);  // πŸ’₯ Object is possibly undefined

// βœ… Check for undefined
if (user) {
    console.log(user.name);
}
// Or use optional chaining
console.log(user?.name);

Fix 2: Parameter Implicitly Has β€˜any’ Type

// ❌ noImplicitAny
function greet(name) {  // πŸ’₯ Parameter 'name' implicitly has 'any' type
    return `Hello ${name}`;
}

// βœ… Add type annotation
function greet(name: string): string {
    return `Hello ${name}`;
}

Fix 3: Type β€˜X’ Is Not Assignable to Type β€˜Y’

// ❌ strictNullChecks
let name: string = getName();  // πŸ’₯ If getName() can return undefined

// βœ… Widen the type
let name: string | undefined = getName();
// Or assert non-null (if you're sure)
let name: string = getName()!;

Fix 4: Enable Strict Incrementally

// Instead of "strict": true, enable flags one at a time:
{
    "compilerOptions": {
        "noImplicitAny": true,          // Start here
        "strictNullChecks": true,        // Then this
        "strictFunctionTypes": true,     // Then this
        "strictPropertyInitialization": true
    }
}

Fix 5: Class Property Not Initialized

// ❌ strictPropertyInitialization
class User {
    name: string;  // πŸ’₯ Not initialized in constructor
}

// βœ… Initialize or use definite assignment
class User {
    name: string = '';  // Default value
    // Or
    name!: string;  // Definite assignment assertion
}

Fix 6: Use @ts-expect-error Temporarily

// βœ… Suppress one error while migrating
// @ts-expect-error β€” TODO: fix this type
const result = legacyFunction(data);

Don’t use @ts-ignore β€” @ts-expect-error will warn you when the error is fixed.

Related: What is TypeScript

πŸ“˜