Forbidden non-null assertion
22 },
23 ];
24 return (
25 <GraphWrapper title={"Memory"} subtitle={`${humanFileSize(memoryLoad[memoryLoad.length - 1]!.loadInBytes)} / ${humanFileSize(maxAvailableBytes)}`} showSubtitle={hasLast}>26 <ResponsiveLine
27 data={data}
28 margin={{ top: 10, right: 10, bottom: 10, left: 10 }}
Forbidden non-null assertion
20 },
21 ];
22 return (
23 <GraphWrapper title={"CPU"} subtitle={`${cpuLoad[cpuLoad.length - 1]!.sumLoad.toFixed(2)}%`} showSubtitle={hasLast}>24 <ResponsiveLine
25 data={data}
26 margin={{ top: 10, right: 10, bottom: 10, left: 10 }}
Description
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 {
// ...
}
Bad Practice
// 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;
Recommended
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;
// ...
}