Forbidden non-null assertion
99 const m = tokens[idx].info.trim().match(/^details\s+(.*)$/);
100 if (tokens[idx].nesting === 1) {
101 return `<details class="custom-block details"><summary>${md.utils.escapeHtml(
102 m![1]103 )}</summary>\n`;
104 } else {
105 return "</details>\n";
Forbidden non-null assertion
86 const m = tokens[idx].info.trim().match(/^info\s+(.*)$/);
87 if (tokens[idx].nesting === 1) {
88 return `<div class="custom-block info"><p class="custom-block-title">${md.utils.escapeHtml(
89 m![1] 90 )}</p>\n`;
91 } else {
92 return "</div>\n";
Forbidden non-null assertion
73 const m = tokens[idx].info.trim().match(/^danger\s+(.*)$/);
74 if (tokens[idx].nesting === 1) {
75 return `<div class="custom-block danger"><p class="custom-block-title">${md.utils.escapeHtml(
76 m![1] 77 )}</p>\n`;
78 } else {
79 return "</div>\n";
Forbidden non-null assertion
60 const m = tokens[idx].info.trim().match(/^warning\s+(.*)$/);
61 if (tokens[idx].nesting === 1) {
62 return `<div class="custom-block warning"><p class="custom-block-title">${md.utils.escapeHtml(
63 m![1] 64 )}</p>\n`;
65 } else {
66 return "</div>\n";
Forbidden non-null assertion
47 const m = tokens[idx].info.trim().match(/^tip\s+(.*)$/);
48 if (tokens[idx].nesting === 1) {
49 return `<div class="custom-block tip"><p class="custom-block-title">${md.utils.escapeHtml(
50 m![1] 51 )}</p>\n`;
52 } else {
53 return "</div>\n";
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;
// ...
}