Forbidden non-null assertion
155 key = this.__renderKeys[0];
156 }
157 const render = this.render2D(params, key);
158 render.fillColor!.alpha = 0.5;159 return render;
160 }
161}
Forbidden non-null assertion
162 key = this.__renderKeys[0];
163 }
164 const render = this.render2D(params, key);
165 render.fillColor!.alpha = 0.5;166 return render;
167 }
168}
Forbidden non-null assertion
166 key = this.__renderKeys[0];
167 }
168 const render = this.render2D(params, key);
169 render.fillColor!.alpha = 0.5;170 return render;
171 }
172}
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;
// ...
}