简体   繁体   English

Typescript 无法识别来自 function 的支票

[英]Typescript not recognizing checks from function

I have a function that validates input我有一个验证输入的 function

export const isValidString = (value: string | null | undefined): boolean => {
  return value != null && value.length > 0 && value.trim() != "";
};

const func = (input: string) =>{
  // some code
}

const someFunction = (input : string | null | undefined) => {
   if(isValidString(input)){
     func(input); //This is the line that is complaining
  }
};

the call to the func is throwing an error which I'm not sure why as the isValidString is making sure the input is not undefined.对 func 的调用引发了一个错误,我不确定为什么isValidString确保输入不是未定义的。 Any reason why?有什么理由吗?

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2345)

However, if I just do但是,如果我只是这样做

if(input != null) func(input);

Everything works一切正常

When isValidString() only returns a boolean , typescript does not know that you have checked that your type is a string now.isValidString()只返回boolean时, typescript 不知道您现在已经检查过您的类型是string

Eg when you hoover over the input variable in this typescript playground example , you can see that the type is still string | undefined | null例如,当您将鼠标悬停在此typescript 操场示例中的input变量上时,您可以看到类型仍然是string | undefined | null string | undefined | null 在此处输入图像描述

To change that, your function must be a type-guard要改变这一点,您的 function 必须是类型保护

export const isValidString = (value: string | null | undefined): value is string => {

Note, the return type of the function is now value is string注意,function 的返回类型现在value is string

When you hoover over input in the new example , you can see that the type is now string当您将鼠标悬停在新示例中的input上时,您可以看到类型现在是string

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

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