【问题标题】:How to tell typescript that an error will be thrown if an argument is null?如果参数为空,如何告诉打字稿将抛出错误?
【发布时间】:2023-02-20 22:08:31
【问题描述】:

假设如下:

const handleParse = (arg: { value: boolean } | null) => {
    if (!arg?.value) {
        throw new Error(`\`arg\` is null`)
    }
    
    return arg.value;
}

在这里,Typescript 知道内联,返回的 arg.value 将始终被定义。

但是,我试图将抛出的错误重构为辅助方法,但它抛出了一个错误:

const checkDependency = (dependency: any) => {
    if (!dependency) {
        throw new Error(`\`dependency\` is null`)
    }
}

const handleParse = (arg: { value: boolean } | null) => {
    checkDependency(arg)
    
    return arg.value;
//         ^^^ 'arg' is possible null
}

我怎样才能做到这一点?我试过使用返回类型,但无济于事:

const checkDependency = (dependency: any):  Error | void  => {
    if (!dependency) {
        throw new Error(`\`arg\` is null`)
    }

    return;
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以为此使用 type assertion function

    function checkDependency<T>(arg: T | null): asserts arg is T {
    // −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^
        if (arg === null) {
            throw new Error(``arg` is null`);
        }
    }
    

    这是您使用它的示例:

    const handleParse = (arg: { value: boolean } | null) => {
        checkDependency(arg);
        
        return arg.value; // <== No error
    };
    

    Full example on the Playground

    【讨论】:

      【解决方案2】:

      也许你可以尝试重载:

      function handleParse(arg: { value: boolean }): void;
      function handleParse(arg: null): never;
      function handleParse(arg: { value: boolean } | null): void | never {
        if (arg === null) {
          throw new Error();
        }
      
        return;
      }
      
      
      handleParse({ value: true});
      console.log('This code is highlighted by TS as reachable');
      
      handleParse(null);
      console.log('This code is highlighted by TS as NOT reachable')
      

      REPL

      它不是相当告诉将抛出一个错误,但至少它表示之后不会运行任何代码。

      【讨论】:

        猜你喜欢
        • 2020-12-02
        • 2020-07-08
        • 2019-06-30
        • 2020-06-02
        • 2019-11-10
        • 1970-01-01
        • 2022-11-18
        • 2016-07-21
        • 1970-01-01
        相关资源
        最近更新 更多