微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何跳过打字稿 linter“空检查”,因为它已经在“assert”函数中完成

如何解决如何跳过打字稿 linter“空检查”,因为它已经在“assert”函数中完成

我创建了一个“断言”函数,它检查条件并在条件失败时抛出适当的错误。它的存在是为了从代码库中删除 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 举报,一经查实,本站将立刻删除。