javascript - 需要帮助理解令人困惑的 Typescript 功能

标签 javascript typescript typescript-generics

我遇到了以下代码,它是数组上的过滤器回调函数。我很困惑试图理解这个函数在做什么,并试图把它分解成更小的部分来理解,但我似乎无法理解它。
我正在尝试学习 TypeScript 并了解一些 JS,但语法让我感到困惑。
有人可以解释一下这个函数如何在数组输入上运行吗?对本示例中的语法进行某种演练会很有帮助。谢谢。

const check = (Boolean as any) as <T>(
  a: T | false | undefined | null | ''
) => a is T;

最佳答案

好吧,这个功能有点……疯狂。让我们稍微分解一下这段代码。
首先,以下面的成语为例:

const something = ('' as any) as boolean
// something's type is boolean for Typescript, but its value is actually a string!
(X as any) as Y idiom 是一种 hack,它可以让你告诉 typescript 某物实际上是另一物。您正在完全控制类型系统,Typescript 将无法推断出潜在的值(value)——更不用说捕捉它了。它可能会导致错误,例如上面的示例,我告诉 TS 一个空字符串是一个 bool 值。
现在,考虑下一个成语:
const isTruthy: <T>( x: T | false | undefined | null | '' ) => x is T
// not yet implemented
这个声明告诉 typescript “这是一个接受任何类型参数的函数,如果它返回 true,则意味着该参数绝对不是假的”。这是通过使用 来完成的。类型保护 通过返回类型“x 是 T”。这很有用,因为它允许您获取一个可能的假值并验证它实际上不是假的:
const a: any[] | null | undefined = [];
if(isTruthy(a)) {
  // a is any[]
}
一种非常简单的实现方式isTruthy是通过使用 Boolean功能:
type Falsy = null | undefined | false | 0 | ''
function isTruthy<T>(value: T | Falsy): value is T {
  return Boolean(value);
}

那么,有什么意义呢?
让我们再次看一下您的示例:
const check = (Boolean as any) as <T>(
  a: T | false | undefined | null | ''
) => a is T;
  • Boolean在这段代码中是一个值。具体来说,它是 bool 函数。
  • 它被转换为 any然后转换为 <T>( x: T | false | undefined | null | '' ) => x is T

  • 所以,这段代码所做的只是为 Boolean 声明一个别名。函数并告诉 TS 它是一个类型保护,如果 check(a)返回真,然后 a不是假的。
    或者你可以,你知道,只检查值本身:
    type Falsy = null | undefined | false | 0 | ''
    const a: string | Falsy = 'test'
    if (a) {
      // a is inferred to be just "string"
    }
    
    TL;博士
    你的“检查”函数做了一些巧妙的技巧来重用 Boolean功能来做一个简单的if()已经可以了。
    只需使用 if(value) 检查值的真实性继续前进
    <编辑>
    我错过了问题的一个重要部分:

    Could someone please explain how this function would operate on an arrays inputs please? a sort of walk through of the syntax in this exampled would be helpful. Thanks.


    在这种情况下,您的 check函数可以与 filter 一起使用一些不错的类型推断的方法:
    
    const arr = ['a', false, 123, 0, '', null, undefined];
    
    arr.filter(Boolean).forEach(value => {
      // value is possibly falsy even though the `filter` makes sure it isn't
    });
    
    const check = (Boolean as any) as <T>(
      a: T | false | undefined | null | ''
    ) => a is T;
    
    arr.filter(check).forEach(value => {
      // value is string | number | true
    });
    
    这是因为 Typescript 无法判断 bool 函数也可以作为 guard 正常工作。这就是您的check 的一个很好的用例。函数,虽然我将它重命名为 isTruthy .

    关于javascript - 需要帮助理解令人困惑的 Typescript 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65429424/

    相关文章:

    Angular ngrx : guards with side-effect

    node.js - 导出类静态方法

    TypeScript:是否可以安全地访问给定键数组的对象的嵌套属性?这可以以类型安全且可组合的方式完成吗?

    typescript - 映射类型不是数组类型

    javascript - HTML5 音频元素 - 某些 Android 浏览器错误报告的音轨长度

    typescript - 将数据传递给根 Vue 类组件

    javascript - 抑制或解决 goog.base 中的编译器错误

    javascript - 键入用于将值添加到数组的通用函数,该数组是对象的属性

    javascript - 聚光灯视频播放器 ||如何用它播放 HTML5 视频

    javascript - 复制 HTML div 的值