Steven Tsao
Steven Tsao

Reputation: 100

How to enable warning from TypeScript when trying to access properties of an optional field?

Accessing property of undefined is a common error in JS. Is there a way that TypeScript can help prevent the following error?

class Person {
    name?: {
        firstName: string;
        lastName: string;
    };
    age: number;
}

let bob: Person = {
    age: 20
}

console.log(bob.name.firstName) // no expected warning

Upvotes: 3

Views: 223

Answers (1)

basarat
basarat

Reputation: 276255

Is there a way that TypeScript can help prevent

Use --strictNullChecks.

More

Upvotes: 3

Related Questions