问题描述
我创建了一个“断言”函数,它检查条件并在条件失败时抛出适当的错误。它的存在是为了从代码库中删除 if/else。
export function assert(predicate : boolean,err: any) {
if(!predicate) throw err;
}
我正在 assert 函数中进行“空检查”,但 tslint 显示“对象可能为‘空’。”
public async run(params: LoginUserDTO,context: any): Promise<LoginUserResponse>
{
await this.validateInput(params);
const {email,password} = params;
const user: User | null = await this.userRepository.getByEmail(email);
// I'm doing "null-checking" here
assert(!!user,new EmailOrPasswordDidNotMatchError());
// Linter is showing warning here,"user is possibly 'null'."
assert(user.isEmailVerified,new EmailNotVerifiedError());
// Linter is showing warning here,"user is possibly 'null'."
const passwordMatched = await Password.compare(password,user.password);
// Linter is showing warning here,"user is possibly 'null'."
assert(passwordMatched,new EmailOrPasswordDidNotMatchError());
// Linter is showing warning here,"user is possibly 'null'."
const loginTokens = await this.getLoginTokens(user);
return new LoginUserResponse(loginTokens.accesstoken,loginTokens.refreshToken);
}
有什么办法可以处理这种情况吗?要么 如果我之前有断言,我如何编写自定义 tslint 规则以跳过“空检查”?
更新: 感谢@OlegValter,我找到了处理这个问题的方法。这是更新的“断言”功能,我添加了断言 singnature
function assert(predicate : boolean,err: any) : asserts predicate {
if(!predicate) throw err;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)