75 function updateTask(id: string): void {
76 const text = prompt("Item Name");
77 const quantity = prompt("Quantity");
78 const data = JSON.parse(localStorage.getItem("itemAdded")!) as object | any; 79
80 const myData = data.map((x: { id: string }) => {
81 if (x.id === id) {
17 const [showItem, setShowItem] = useState(false);
18
19 /* https://stackoverflow.com/a/46915314/11986604 */
20 const getGrocery = JSON.parse(localStorage.getItem("itemAdded")!) as object; 21
22 /**
23 * Read
Using non-null assertions cancels out the benefits of strict null-checking, and introduces the possibility of runtime errors. Avoid non-null assertions unless absolutely necessary. If you still need to use one, write a skipcq comment to explain why it is safe.
Ideally, you want to have a validation function that confirms a value isn't null, with a return type like this:
type AccentedColor = `${Color}-${Accent}`
function isColorValid(name: string): name is AccentedColor {
// ...
}
// a user named "injuly" may not exist in the DB
const injuly: User | null = db.getUserByName("injuly");
// Using the non-null assertion operator will bypass null-checking
const pfp = injuly!.profilePicture;
const injuly: User | null = db.getUserByName("injuly");
const pfp = injuly?.profilePicture; // pfp: Image | undefined
// OR:
const pfp_ = injuly ? injuly.pfp : defaultPfp; // pfp: Image
Alternatively:
function isUserValid(userObj: User | null | undefined ): userObj is User {
return Boolean(userObj) && validate(userObj);
}
const injuly = db.getUserByName("injuly")
if (isUserValid(injuly)) {
const pfp = injuly.profilePicture;
// ...
}