简体   繁体   English

从在 Typescript 中抛出 function 的错误推断类型?

[英]inferring types from an Error throwing function in Typescript?

I have a function below, that checks if myValue exists before calling doSomething() , if it does not exist, it will throw.我在下面有一个 function ,它在调用doSomething()之前检查myValue是否存在,如果不存在,它将抛出。 Typescript accepts this... Typescript 接受这个...

function myFunction(){
   if (!myValue) {
     const error = Error(errorName);
     error.name = errorName.replace(/\s+/g, "-").toLowerCase();
     throw error;
   }

   const something = doSomething(myValue);
}

The below implementation makes a Helper Function for throwing a named Error.下面的实现使一个助手 Function 用于抛出一个命名的错误。 Typescript doesn't like this, and errors that doSomething(myValue) is being passed myValue which is potentially undefined. Typescript 不喜欢这样,并且传递doSomething(myValue)的错误myValue可能是未定义的。 How can I type the namedError so that it has the inferred typing from above, that it is Truthy?如何键入namedError以便它具有从上面推断的类型,它是真实的?

function myFunction(){
   if (!myValue) {
     namedError("my value doesn't exist");
   }

   const something = doSomething(myValue);
}

function namedError(errorName: string){
  const error = Error(errorName);
  error.name = errorName.replace(/\s+/g, "-").toLowerCase();
  throw error;
};

Since typescript 3.7 functions that return never have the same impact in control flow analysis as a throw expression.从 typescript 3.7开始,返回的函数在控制流分析中的影响neverthrow表达式相同。 So this will work:所以这将起作用:


let myValue: string | undefined;

function myFunction() {
  if (!myValue) {
    namedError("my value doesn't exist");
  }

  const something = doSomething(myValue);
}

function namedError(errorName: string): never {
  const error = Error(errorName);
  error.name = errorName.replace(/\s+/g, "-").toLowerCase();
  throw error;
};

function doSomething(value: string) {

}

Playground Link 游乐场链接

Typescript null elimination doesn't work with nest function calls (unless it's an immediately invoked function expression) hence the error. Typescript null elimination doesn't work with nest function calls (unless it's an immediately invoked function expression) hence the error. You can either move the doSomething invocation into an else block, or use the type assertion operator when you are sure a value will not be null or defined.您可以将 doSomething 调用移动到 else 块中,或者当您确定某个值不会是 null 或未定义时使用类型断言运算符。

So either:所以要么:

if (!myValue) {
  namedError(...)
} else {
  const something = doSomething(myValue);
}

or或者

if (!myValue) {
  namedError(...)
}

// use type assertion (! postfix) to tell compiler that the value will never be null or undefined
const something = doSomething(myValue!);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM