混淆了推断的返回类型

huangapple go评论61阅读模式
英文:

Confusion on inferred return type

问题

以下是翻译好的部分:

我正在使用 TypeScript,并对编译器如何不同地推断这两个函数的返回类型感到困惑。

// 这个的类型是 () => boolean | ""
const isFormValid = () => {
return jobTitle && jobTitle !== ''
}

// 这个的类型是 () => boolean
const isFormInvalid = () => {
return !jobTitle || jobTitle === ''
}

是的,jobTitle 是一个字符串,但这两个函数的返回类型都应该是 () => boolean 吗?

英文:

I was working with Typescript and got confused with how the compiler infers the return types differently for these two functions.

//this is of type () => boolean | ""
const isFormValid = () => {
  return jobTitle && jobTitle!=''
}

//this is of type () => boolean
const isFormInvalid = () => {
  return !jobTitle || jobTitle===''
} 

Yes, jobTitle is a string, but shouldn't both of these be of return type () => boolean?

答案1

得分: 2

isFormValid('') === '' // true

如果您想要布尔值作为返回值,请使用两个叹号 !

const isFormValid = () => {
  return !!jobTitle && jobTitle!=''
}
英文:
isFormValid('') === '' // true

If you want boolean as returned value use double !:

const isFormValid = () => {
  return !!jobTitle && jobTitle!=''
}

</details>



# 答案2
**得分**: 2

`a && b`返回`a`,如果它是“假值”。`0`,`null`,`undefined`和空字符串都是“假值”。

<details>
<summary>英文:</summary>

`a &amp;&amp; b` returns `a` if it&#39;s &quot;falsy&quot;. `0`, `null`, `undefined` and the empty string are all &quot;falsy&quot;.

</details>



# 答案3
**得分**: 2

以下是您要的翻译内容:

这是预期的行为。为了解释,让我们从`||`运算符开始。
如果左边的值是假的,`||`会取右边的值。

```javascript
const value = false || 0 // 0
const value2 = true || 0 // true

"" 也被视为假值:

const value3 = "" || "str" // "str"

而对于&&运算符,如果左边的值是假的,它会赋予左边的值,否则赋予右边的值:

const value1 = false && "str" // false;
const value2 = true && "str"  // str;

由于jobTitle是一个string,它也可以是"",编译器会推断两种可能的返回值:

  1. jobTitle"" 时: ""
  2. jobTitle不是 "" 时: jobTitle === '' 的布尔值。
英文:

It is expected behavior. For explanation, let's start with || operator.
|| takes the value on the right side if the value on the left is falsy.

const value = false || 0 // 0
const value2 = true || 0 // true

The &quot;&quot; is also considered a falsy value:

const value3 = &quot;&quot; || &quot;str&quot; // &quot;str&quot;

With the &amp;&amp;, it assigns the left value if it is falsy, otherwise the right one:

const value1 = false &amp;&amp; &quot;str&quot; // false;
const value2 = true &amp;&amp; &quot;str&quot;  // str;

Since jobTitle is a string it can be &quot;&quot; as well and compiler infers the two possible return values:

  1. When jobTitle is &quot;&quot;: &quot;&quot;
  2. When jobTitle is not &quot;&quot;: jobTitle === &#39;&#39; boolean

huangapple
  • 本文由 发表于 2023年5月10日 23:44:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220378.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定