Inside tsconfig.json there is flag
"strictNullChecks": true
Suppose you have code like below
declare const loggedInUsername: string;
const users = [
{ name: "Oby", age: 12 },
{ name: "Heera", age: 32 },
];
const loggedInUser = users.find((u) => u.name === loggedInUsername);
console.log(loggedInUser.age);
Here in last statement we are printing age of filtered loggedInUser variable but if if have no record in loggedInUser then loggedInUser is undefined
so if we set
"strictNullChecks": true
we get error .
How to resolve this
const users = [
{ name: "Oby", age: 12 },
{ name: "Heera", age: 32 },
];
const loggedInUser = users.find((u) => u.name === loggedInUsername);
console.log(loggedInUser!.age);
or
declare const loggedInUsername: string;
const users = [
{ name: "Oby", age: 12 },
{ name: "Heera", age: 32 },
];
const loggedInUser = users.find((u) => u.name === loggedInUsername);
if(loggedInUser){
console.log(loggedInUser.age);
}
No comments:
Post a Comment